Search code examples
c#httprequestrestful-urlasp.net-web-api-routingcontroller-actions

How can I access the args on the RESTful URL from a Controller?


I asked a preliminary and somewhat similar question here.

Now I need to know how to access the values from within a RESTful URL inside a Controller method/action.

I have a Controller named PlatypusController with a route for it set up like this in WebApiConfig:

config.Routes.MapHttpRoute(
    name: "ReportsApi",
    routeTemplate: "api/{controller}/{unit}/{begindate}/{enddate}",
    defaults: new { enddate = RouteParameter.Optional }
);

PlatypusController.cs has this code:

public void Post()
{
    int i = 2; 
}

The "int i = 2" is nonsense, of course; I just put it there so I could put a breakpoint in the method to verify it was reached. It is when I select "POST" and enter this URL in Postman:

http://localhost:52194/api/Platypus/gramps/201509

(the app is running on port 52194 when I call this)

But to accomplish something worthwhile, I need the "gramps" and the "201509" from the URL. How can I access those? Do I need to add them to the Post method something like this:

public void Post(string unit, string begindate)
{
    DoSomething_Anything(unit, begindate);
}

...or is there some other way to get them, such as from a HttpRequest object or something?


Solution

  • I personally prefer to be explicit when defining my routes and that's why I recommend attribute routing instead of convention based routing.

    That way, you can explicitly configure routing per controller and action.

    Instead of configuring routes this way in the WebApiConfig, just make sure that you have initialized attribute routing by calling this line:

    config.MapHttpAttributeRoutes();
    

    in the WebApiConfig file.

    Then you can do something like this:

    [RoutePrefix("api/platypus")]
    public class PlatypusController: ApiController
    {
         [Route("{unit}/{begindate}")]
         [HttpPost]
         public void Post(string unit, string begindate)
         {
             int i = 2; 
         }
    }
    

    To call this method, do a POST request to: /api/platypus/gramps/201509