[英]web api: Route different from name of controller, possible?
I have mineController.cs now in my route, is it possible to do /api/mycontroller/myaction 我的路线中现在有mineController.cs,可以执行/ api / mycontroller / myaction
ie I try to get route not limit to controller name 即我尝试获取路由不限于控制器名称
Yes, by using Attribute Routing. 是的,通过使用属性路由。
Step 1: Enable attribute routing in WebApiConfig.Register
method (might be on by default, I don't recall offhand): 第1步:在
WebApiConfig.Register
方法中启用属性路由(默认情况下可能处于启用状态,我不会立即记起):
config.MapHttpAttributeRoutes();
Step 2: Not required, but it's nice to use a RoutePrefix
attribute for the entire controller: 步骤2:不是必需的,但是最好对整个控制器使用
RoutePrefix
属性:
[RoutePrefix("api/mycontroller")
public class mineController : ApiController
{
..
}
Step 3: Use a Route
attribute on each method that completes the route prefix: 步骤3:在每个用于完成路由前缀的方法上使用
Route
属性:
[Route("myaction")]
[HttpGet] /* or other HttpVerb */
public IHttpActionResult SomeMethod()
{
...
}
[Route("myaction/{id}")]
[HttpGet] /* or other HttpVerb */
public IHttpActionResult SomeMethod(int id)
{
...
}
More info here: https://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2 此处提供更多信息: https : //www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2
If you are using Web Api 2 you can use Attribute Routing for this: 如果您使用的是Web Api 2,则可以为此使用“ 属性路由 ”:
[RoutePrefix("api/mine")]
public class mineController : ApiController
{
[Route("method1")]
[HttpGet]
public IHttpActionResult Method1()
{
//Route would be api/mine/method1
}
[Route("method2")]
[HttpGet]
public IHttpActionResult Method2()
{
//Route would be api/mine/method2
}
}
You can use the System.Web.Http.RouteAttribute
to decorate your controller actions and specify any route you desire. 您可以使用
System.Web.Http.RouteAttribute
装饰您的控制器操作并指定所需的任何路由。 Depending on what it is you want to do, this may be a good approach for you. 根据您要执行的操作,这可能是您的一种好方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.