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

Multiple POST-request in web api


I need to use multiple POST-requests in web API but get an error: "Multiple actions were found that match the request..."

I have 2 POST-requests in my controller:

public void PostStart([FromBody]string value)
{
    CookieHeaderValue cookie = Request.Headers.GetCookies("user").FirstOrDefault();
    ...
}


public void PostLogin([FromBody]string value)
{
    CookieHeaderValue cookie = Request.Headers.GetCookies("user").FirstOrDefault();
    ...
}

My route file looks like this currently:

public static void Register(HttpConfiguration config)
{
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "apistart",
        routeTemplate: "Home/api/values/start/{id}",
        defaults: new { action = "PostStart", id = RouteParameter.Optional }
    );

    config.Routes.MapHttpRoute(
        name: "apilogin",
        routeTemplate: "Home/api/values/login/{id}",
        defaults: new { action = "PostLogin", id = RouteParameter.Optional }
    );

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

If I remove on of the requests from the controller, everything works fine, so my routes seem valid, but when both of requests are present, router can't find the right one.

Any thoughts? I've tried alredy to use another default route but it changes nothing:

routes.MapHttpRoute(
    name: "ActionApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

Solution

  • You can use [HttpPost] attribute to specify request method:

    [HttpPost]
    public void Start([FromBody]string value)
    {
        CookieHeaderValue cookie = Request.Headers.GetCookies("user").FirstOrDefault();
        ...
    }
    
    [HttpPost]
    public void Login([FromBody]string value)
    {
        CookieHeaderValue cookie = Request.Headers.GetCookies("user").FirstOrDefault();
        ...
    }
    

    That will allows you to use as many post actions as you want with using default action-based route rule.

    routes.MapHttpRoute(
        name: "ActionApi",
        routeTemplate: "api/{controller}/{action}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );