ASP.NET网页API 2 - 属性基于策略的路由 - 如何强制参数只能查询字符串? [英] ASP.NET Web Api 2 - Attribute Based Routing - How do I force a parameter to query string only?

查看:107
本文介绍了ASP.NET网页API 2 - 属性基于策略的路由 - 如何强制参数只能查询字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个网页API 2项目,我使用基于属性的路由。下面是一个示例路线:

I am working on a Web Api 2 project and I am using attribute based routing. Here is a sample route:

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

这适用于以下网址:


  • ://主机/员工/ 12345

  • ://主机/员工ID = 12345

我想preFER是第一种形式(URI中的参数),将不会被允许的,只有第二种形式(查询字符串)会的工作。

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.

大多数情况下,我试着在网上搜索的方法,使这项工作,我没有找到太多。

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?).

<一个href=\"http://forums.asp.net/t/1920979.aspx?Web%20Api%202%20$p$pview%20and%20Attribute%20Routing%20allowing%20querystrings%20\"相对=nofollow>此页面实际上并不prevent从工作URI形式。

This page doesn't actually prevent the URI form from working.

推荐答案

其实,我错了我原来的code。查询字符串参数不与我指定的路线运行。相反,我可以这样做:

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)
{
    ...
}

这将做我想做的。它一定是名 ID 从函数的参数列表。

不幸的是,这意味着我不能把一个约束它了,但我想我可以在函数中只是验证。

Unfortunately, this means I can't put a constraint on it anymore, but I guess I can just validate within the function.

这篇关于ASP.NET网页API 2 - 属性基于策略的路由 - 如何强制参数只能查询字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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