Search code examples
asp.net-corehttp-method

Create a custom Http method


Is it possible to create our own HTTP method by just overriding the HttpMethodAttribute class and specify our own supportedMethods ?

In fact, depending on the case, we need to return the View as complete view with the _Layout, and sometimes we just need to return the PartialView of this view. So my idea is to put an custom attribute, like [HttpPartial] and so the client will tell, depending on the methods used in the request, if it wants the complete view (GET method) or the partial view (PARTIAL method).


Solution

  • Yes, that's possible for APIs. You can look at how the HttpGetAttribute is implemented, and roll your own for a custom method, replacing "get" with "foo":

    /// <summary>
    /// Identifies an action that supports the HTTP FOO method.
    /// </summary>
    public class HttpFooAttribute : HttpMethodAttribute
    {
        private static readonly IEnumerable<string> _supportedMethods = new[] { "FOO" };
    
        /// <summary>
        /// Creates a new <see cref="HttpFooAttribute"/>.
        /// </summary>
        public HttpFooAttribute()
            : base(_supportedMethods)
        {
        }
    
        /// <summary>
        /// Creates a new <see cref="HttpFooAttribute"/> with the given route template.
        /// </summary>
        /// <param name="template">The route template. May not be null.</param>
        public HttpFooAttribute(string template)
            : base(_supportedMethods, template)
        {
            if (template == null)
            {
                throw new ArgumentNullException(nameof(template));
            }
        }
    }
    

    Then apply it to your API action methods:

    [Route("Bar")]
    public class BarApiController : Controller
    {
        [HttpFoo("/"]
        public IActionResult Foo()
        {
            return Ok("Foo");
        }
    }
    

    Now you can request FOO https://your-api:44312/bar/.

    This is less useful for actions returning views, as any HTML-rendering user agent only lets the user initiate GET or POST requests through hyperlinks and forms.

    You could send more methods through an XMLHttpRequest or fetch(), but it'll require more documentation and client customization.

    Don't break or hamper the web, don't invent new HTTP methods for your application logic. Simply use a query string parameter or send it in your body: &renderAsPartial=true, { "renderAsPartial": true }.

    See the IANA's Hypertext Transfer Protocol (HTTP) Method Registry for existing methods and see RCF 7231 section 8.1 for how to register new HTTP methods.