[英]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. 我正在编写REST Web API,我需要使用POST方法使端点类似于/ api / users / {id} / modify或http:// localhost:8080 / api / users / 6 / modify 。
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. 我有一个具有所有读/写操作的UsersController类,但是我只能通过访问/ api / users而不是/ api / users / 6 / modify来访问post方法。 I need to expand the hierarchy(if that is well said). 我需要扩展层次结构(如果说得好)。
How can I do to achieve this? 我该怎么做呢?
You can use the Attribute Routing of asp.net web api. 您可以使用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. 首先是通过asp.net web api模板中的HttpConfiguration
启用它,您可以在WebApiConfig.cs
文件上看到它。
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: 之后,您可以定义一个控制器,该控制器应继承自ApiController
并可以使用Route
属性定义示例的自定义路由:
[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. RoutePrefix
将为控制器上的所有操作定义一个前缀。 So, to access the PostModify
you should use a route like /api/users/6/modify
in a post
action. 因此,要访问PostModify
您应该在post
操作中使用类似/api/users/6/modify
的路由。 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
. 如果您不想要它,只需删除RoutePrefix
并在route属性上定义完整的url,如下所示: /api/users/{id}/modify
。
You also can guarantee the type of the id
argument defining a route like this: 您还可以保证定义这样的路由的id
参数的类型:
[RoutePrefix("api/users")]
public class UsersController : ApiController
{
[HttpPost]
[Route("{id:int}/modify")]
public HttpResponseMessage PostModify(int id)
{
// code ...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.