asp.net-mvc - 如何将查询字符串映射到 MVC 中的操作方法参数?

标签 asp.net-mvc asp.net-mvc-routing

我有一个网址 http://localhost/Home/DomSomething?t=123&s=TX我想将此 URL 路由到以下操作方法

public class HomeController
{
   public ActionResult DoSomething(int taxYear,string state)
   {
      // do something here
   }
}

由于查询字符串名称与操作方法的参数名称不匹配,因此请求不会路由到操作方法。

如果我将 url(仅用于测试)更改为 http://localhost/Home/DomSomething?taxYear=123&state=TX然后它的工作。 (但我无权更改请求。)

我知道有 Route属性我可以应用于操作方法并且可以映射 ttaxYearsstate .

但是,我没有找到此映射的 Route 属性的正确语法,有人可以帮忙吗?

最佳答案

选项1

如果查询字符串参数始终是 t 和 s,则可以使用 Prefix。请注意,它将不再接受 taxYear 和 state。

http://localhost:10096/home/DoSomething?t=123&s=TX

public ActionResult DoSomething([Bind(Prefix = "t")] int taxYear, 
   [Bind(Prefix = "s")] string state)
{
    // do something here
}

选项 2

如果要同时接受两个 URL,则声明所有参数,并手动检查哪个参数具有值 -
http://localhost:10096/home/DoSomething?t=123&s=TX
http://localhost:10096/home/DoSomething?taxYear=123&state=TX

public ActionResult DoSomething(
    int? t = null, int? taxYear = null, string s = "",  string state = "")
{
    // do something here
}

选项 3

如果你不介意使用第三方包,你可以使用 ActionParameterAlias .它接受两个 URL。
http://localhost:10096/home/DoSomething?t=123&s=TX
http://localhost:10096/home/DoSomething?taxYear=123&state=TX

[ParameterAlias("taxYear", "t")]
[ParameterAlias("state", "s")]
public ActionResult DoSomething(int taxYear, string state)
{
    // do something here
}

关于asp.net-mvc - 如何将查询字符串映射到 MVC 中的操作方法参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41969112/

相关文章:

c# - MVC 路由 : How to map two names to one action

asp.net-mvc - ASP.NET MVC 将非 WWW 重定向到 WWW 并重写为小写 URL

asp.net - ASP.NET MVC 3 路由可能存在错误?

asp.net-mvc-3 - Asp.Net MVC 3 - 映射已经属于某个区域的单独路线

asp.net-mvc - 解耦 Microsoft.AspNet.Identity.*

c# - 从 MVC View 调用方法不起作用

c# - 在 WebAPI 帖子中发现了多项操作 - 为什么这不起作用?

c#-4.0 - 从 ASP.NET MVC 3 升级到 MVC 4,参数被替换为路由

asp.net-mvc - REST 风格的 url 路由

c# - 使用asp.net路由url