Robert Pouleijn Robert Pouleijn - 1 month ago 5
ASP.NET (C#) Question

404 when passing web api parameters

I'm trying to get this method to work:

public class DocumentenController : ApiController
{
[HttpPost]
[Route("DeleteDocument/{name}/{planId}")]
public IHttpActionResult DeleteDocument(string name, int planId)
{
_documentenProvider.DeleteDocument(planId, name);
return Ok();
}
}


This is the WebApiConfig :

config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: UrlPrefix + "/{controller}/{action}/{id}",
defaults: new {id = RouteParameter.Optional}
);


But I get a 404 when I call it like this using a post:

http://localhost/QS-documenten/api/documenten/deletedocument/testing/10600349


What is the proper way do solve this?

Answer

The URL in example does not match attribute route on controller.

To get

http://localhost/QS-documenten/api/documenten/deletedocument/testing/10600349

to work, assuming that http://localhost/QS-documenten is the host and root folder, and that api/documenten is the api prefix then add a route prefix to the controller...

[RoutePrefix("api/Documenten")]
public class DocumentenController : ApiController {
    //eg POST api/documenten/deletedocument/testing/10600349
    [HttpPost]
    [Route("DeleteDocument/{name}/{planId}")]
    public IHttpActionResult DeleteDocument(string name, int planId) {
        _documentenProvider.DeleteDocument(planId, name);
        return Ok();
    }
}

Source: Attribute Routing in ASP.NET Web API 2 : Route Prefixes