如何使用属性路由在Web API 2中设置路由 [英] How to setu up a route in web API 2 with attribute routing

查看:73
本文介绍了如何使用属性路由在Web API 2中设置路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我在我的web api 2项目中设置路线时遇到问题。我似乎无法使用属性路由创建这种路由



/ api / {controller} /?object_id = 5



它总是以404作为bact ...



如果输入/ api / {controller} / object?object_id = 5我得到我想要的结果...



有没有办法让这种情况发生?



谢谢,B



我尝试过:



我的路线看起来像这个

Hello im having a problem setting up a route in my web api 2 project. I cannot seem to be able to create this kind of route with attribute routing

/api/{controller}/?object_id=5

It allways comes bact as 404...

If I type /api/{controller}/object?object_id=5 I get the results that I want...

Is there a way to make this happen?

Thanks, B

What I have tried:

My route looks like this

[Route("{object_id}"];

推荐答案

Web API路由的工作方式是你需要添加



The way web API routes work is you need to add

config.MapHttpAttributeRoutes();





如果不存在,请添加到WebApiConfig.cs文件中。 />


然后至于路线你要记住两个属性,RoutePrefix和路线。



所以这样的例子就是





To your WebApiConfig.cs file if it isn't there.

Then as for the route you have two attributes to keep in mind, RoutePrefix and Route.

So an example of this would be

[RoutePrefix("api/people")]
public class PeopleController : Controller
{
   [Route("names")]
   public IHttpActionResult GetNames()
   { 
      var names = //do a DB select operation or something
      return Ok(names);
   }
}





此示例允许您使用网址http:// localhost / api / people / names而不是uglier版本的http:// localhost / people / getnames。



现在对于在web api路由中使用参数的操作,你可以做类似





This example allows you to use the url http://localhost/api/people/names instead of the uglier version of http://localhost/people/getnames.

Now for actions with parameters in web api routes you'd do something like

[RoutePrefix("api/people")]
public class PeopleController : Controller
{
   [Route("names/{personId}")]
   public IHttpActionResult GetNameForPersion(int personId)
   { 
      var names = //do a DB select operation or something
      return Ok(names);
   }
}





这样您就可以在网址中添加代表某人的ID。请记住,操作中的参数名称必须与路径中使用的名称相同。否则我相信你会收到404错误。



所以这个网址就像http:// localhost / api / people / names / 1



如果您还有其他问题,请参考:



ASP.NET Web API 2中的属性路由ASP.NET站点 [ ^ ]


这篇关于如何使用属性路由在Web API 2中设置路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆