MVC-如何从参数名称包含点字符的 get 请求中获取参数值

问题描述 投票:0回答:4

在 MVC 中,我知道我们可以像这样从 get 请求中获取参数:

要求:

http://www.example.com/method?param1=good&param2=bad

在控制器中

public ActionResult method(string param1, string param2)
{
   ....
}

但在我的情况下,外部网站向我发送了一个 get 请求,例如:

http://www.example.com/method?param.1=good&param.2=bad

在控制器中,当我尝试满足此请求时,如下所示:

public ActionResult method(string param.1, string param.2)
{
   ....
}

由于变量名称中的点,我遇到构建错误。我怎样才能得到这些参数?不幸的是我不能要求他们更改参数名称。

asp.net-mvc url parameters get asp.net-mvc-routing
4个回答
45
投票

使用以下代码:

    public ActionResult method()
    {
        string param1 = this.Request.QueryString["param.1"];
        string param2 = this.Request.QueryString["param.2"];

        ...
    }

19
投票

这可能是您最好的选择:

/// <summary>
/// <paramref name="param.1"/>
/// </summary>
public void Test1()
{
    var value = HttpContext.Request.Params.Get("param.1");
}

HttpContext.Request.Params
获取参数而不是将其作为显式参数


1
投票
The Framework
  public void ProcessRequest(HttpContext context)
  {
     string param1 = context.Request.Params["param.1"];

替换为 .net核心3.1

ControllerBase 
  ...
    [ApiController]
    [Route("[controller]")]
   ...

     string param1 = HttpContext.Request.Query["param.1"];
     string param2 = HttpContext.Request.Query["param.2"];

0
投票

也许回复较晚,但很有用。

对于像 nooaa 这样的请求:

http://www.example.com/method?param1=good¶m2=bad

ssimeonov 的解决方案将起作用:

   string param1 = this.Request.QueryString["param1"];
   string param2 = this.Request.QueryString["param2"];

将返回参数。但是,如果 URL 由带参数的 API 调用,request.QueryString 可以返回 null(或空)。

无论如何,最好的解决方案是

   var value = HttpContext.Request.Params.Get("param1");

正如 James Haug 所提议的那样。

© www.soinside.com 2019 - 2024. All rights reserved.