NicoRiff
NicoRiff

Reputation: 4883

Routing Post to a non standard uri web api

I´m writing a REST web api and I need to have an endpoint like /api/users/{id}/modify or http://localhost:8080/api/users/6/modify using a POST method.

I have a UsersController class with al read/write actions but I´m only able to access the post method by accessing /api/users, not /api/users/6/modify. I need to expand the hierarchy(if that is well said).

How can I do to achieve this?

Upvotes: 0

Views: 244

Answers (1)

Felipe Oriani
Felipe Oriani

Reputation: 38638

You can use the Attribute Routing of asp.net web api.

The first thing is to enable it over the HttpConfiguration, in asp.net web api template, you can see it on the WebApiConfig.cs file.

using System.Web.Http;

namespace WebApplication
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API routes
            config.MapHttpAttributeRoutes();

            // Other Web API configuration not shown...
        }
    }
}

After that you can define a controller which should inherits from ApiController and you can use the Route attribute to define a custom route, for sample:

[RoutePrefix("api/users")]
public class UsersController : ApiController
{
    [HttpPost]
    [Route("{id}/modify")]
    public HttpResponseMessage PostModify(int id) 
    { 
       // code ...
    }
}

The RoutePrefix will define a prefix for all actions on the controller. So, to access the PostModify you should use a route like /api/users/6/modify in a post action. If you do not want it, just remove the RoutePrefix and define the complete url on the route attribute, like this: /api/users/{id}/modify.

You also can guarantee the type of the id argument defining a route like this:

[RoutePrefix("api/users")]
public class UsersController : ApiController
{
    [HttpPost]
    [Route("{id:int}/modify")]
    public HttpResponseMessage PostModify(int id) 
    { 
       // code ...
    }
}

Upvotes: 2

Related Questions