简体   繁体   English

ASP.NET Web Api 2-基于属性的路由-如何强制参数仅查询字符串?

[英]ASP.NET Web Api 2 - Attribute Based Routing - How do I force a parameter to query string only?

I am working on a Web Api 2 project and I am using attribute based routing. 我正在研究Web Api 2项目,并且正在使用基于属性的路由。 Here is a sample route: 这是一个示例路线:

[Route("{id:int}", Name = "GetEmployeeById")]
[HttpGet]
public IHttpActionResult GetEmployee(int id)
{
    ...
}

This works with the following URLs: 这适用于以下URL:

  • ://host/employee/12345 ://主机/员工/ 12345
  • ://host/employee?id=12345 ://主机/员工ID = 12345

What I would prefer is that the first form (the parameter in the URI), would not be allowed, and only the second form (query string) would work. 我更希望的是不允许使用第一种形式(URI中的参数),只有第二种形式(查询字符串)可以工作。

What I've Tried 我尝试过的

Mostly, I've tried searching the web for a way to make this work, and I'm not finding much. 通常,我尝试在网络上搜索实现此目的的方法,但并没有发现太多。

This page talks about route constraints but this syntax doesn't seem to work (anymore?). 该页面讨论了路由约束,但是这种语法似乎不起作用(是吗?)。

This page doesn't actually prevent the URI form from working. 该页面实际上并没有阻止URI表单正常工作。

There is an attribute called "[FromUri]" that you can use to decorate a method parameter, and the model binder will try to look for that parameter from the Querystring, it may not help you with this scenario but it is good to know about it, so in case you want to pass a search options for example to a Get method. 有一个名为“ [FromUri]”的属性,您可以用来装饰方法参数,并且模型绑定程序将尝试从Querystring中查找该参数,在这种情况下它可能无济于事,但是很高兴知道因此,如果您要将搜索选项传递给Get方法,例如。

Hope that helps. 希望能有所帮助。

Couple of ways to achieve this. 实现此目的的几种方法。 Here are some options 这里有一些选择

  1. Rename parameter to something else than id (eg. employeeId). 将参数重命名为ID以外的其他名称(例如,employeeId)。
  2. Change the default routing configuration in WebApiConfig: 更改WebApiConfig中的默认路由配置:

      //Default configuration, you can see here the "id" parameter which enables action/id matching config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); //It should look like this config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}" ); 

Also you can do it with custom attributes. 您也可以使用自定义属性。

Actually, I was wrong about my original code. 实际上,我对原始代码有误。 The query string parameter did not work with the route I specified. 查询字符串参数不适用于我指定的路由。 Instead, I could do this: 相反,我可以这样做:

[Route("", Name = "GetEmployeeById")]
[HttpGet]
public IHttpActionResult GetEmployee(int id)
{
    ...
}

And this will do what I want. 这会做我想要的。 It must be getting the name id from the function's parameter list. 它必须从函数的参数列表中获取名称id

Unfortunately, this means I can't put a constraint on it anymore, but I guess I can just validate within the function. 不幸的是,这意味着我不能再对其施加约束了,但是我想我可以在函数中进行验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM