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

How to map querystring to action method parameters in MVC?

我有一个 url 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 属性,它可以将 t 映射到 taxYear 并将 s 映射到 state

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

选项 1

如果查询字符串参数总是ts,那么您可以使用Prefix。请注意,它不再接受 taxYearstate

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
}