Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 477
Niranjan Godbole Avatar asked Oct 27 '25 10:10

Niranjan Godbole


1 Answers

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

like image 127
Nkosi Avatar answered Oct 29 '25 00:10

Nkosi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!