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

Get method not working in web api


Hi I am developing one application in web api2 and angularjs. I have some routing problems in accessing urls from angularjs.

I am trying to access below url.

var url = '/api/projects/4/processes';

My controller code looks like below.

[RoutePrefix("api/processes")]
public class processesController : ApiController
{      
    [ActionName("projects/{projectsId}/processes")]
    public HttpResponseMessage Get(int id)
    {
        return Request.CreateResponse(HttpStatusCode.OK, "");
    }
}

I am getting 404 error. I am not able to hit the url.

This is my webapi.config file.

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    //routeTemplate: "{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

Any help would be appreciated.


Solution

  • First ensure that attribute routing is enabled before convention-based routes.

    config.MapHttpAttributeRoutes();
    
    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",            
        defaults: new { id = RouteParameter.Optional }
    );
    

    if the intended url is /api/projects/4/processes Then the given action needs to update its route template to match. The controller already has a route prefix but that can be overridden by prefixing the route template with the tilde ~

    Use a tilde (~) on the method attribute to override the route prefix:

    //GET /api/projects/4/processes
    [HttpGet]    
    [Route("~/api/projects/{projectsId:int}/processes")]
    public HttpResponseMessage Get(int projectsId) { ... }
    

    Source: Attribute Routing in ASP.NET Web API 2