Search code examples
c#.netasp.net-web-apiasp.net-web-api2asp.net-web-api-routing

ASP.NET Web API 2 custom routing to specific method


How can I configure routing in ASP.NET Web API to route it to specific method in controller with GET method?

http://mysite/healthcheck

Registration in WebAPiConfig looks like this:

    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "HealthCheck",
        routeTemplate: "healthcheck",
        defaults: new { action =" DefaultAction" }
    );

The controller looks like this:

[RoutePrefix("healthcheck")]
public class HealthCheckController : ApiController
{
    [HttpGet]
    [ActionName("DefaultAction")]
    public HttpResponseMessage GetHealthCheckStatus()
    {
        return Request.CreateResponse(HttpStatusCode.OK);
    }    
}

I get Not Found instead of Ok when hitting that URL. Any help would be appreciated

UPDATE Thank you for all the suggestions, I checked them all and none works. The route debugger shows no matches. I am putting this on hold for a while.


Solution

  • In your Startup.cs register attribute routes:

    config.MapHttpAttributeRoutes();
    

    And in the controller:

    [RoutePrefix("healthcheck")]
    public class HealthCheckController : ApiController
    {
        [HttpGet]
        [Route]
        public IHttpActionResult GetHealthCheckStatus()
        {
            return Ok();
        }
    }