【问题标题】:Accessing query string variables sent as POST in HttpActionContext访问在 HttpActionContext 中作为 POST 发送的查询字符串变量
【发布时间】:2016-01-17 00:45:22
【问题描述】:

我正在尝试访问使用 POST 方法 (WebClient) 发送到 ASP.NET MVC 5 中的 Web API 的查询字符串参数(在被覆盖的 AuthorizationFilterAttribute 中)。

对于 Get,我使用了以下技巧: var param= actionContext.Request.GetQueryNameValuePairs().SingleOrDefault(x => x.Key.Equals("param")).Value;

但是,一旦我使用 POST,这确实有效,并且变量 paran 设置为 null。我认为这是因为查询字符串方法仅适用于 url,而不适用于正文。有什么方法可以获取 GET 和 POST 请求的查询字符串(最好使用一种方法)?

编辑:WebClient 代码

using (WebClient client = new WebClient())
{
        NameValueCollection reqparm = new NameValueCollection();

        reqparm.Add("param", param);

        byte[] responsebytes = client.UploadValues("https://localhost:44300/api/method/", "POST", reqparm);
        string responsebody = Encoding.UTF8.GetString(responsebytes);

        return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(responsebody);

    }
}

【问题讨论】:

  • 您似乎来自 PHP 背景。与该语言让您相信的相反 ($_GET),用于请求页面的动词与查询字符串完全无关。就是这样:请求URI中?之后的部分。显示您用于发送 POST 请求的 WebClient 代码;显然你没有在那里正确设置查询字符串参数。
  • @CodeCaster,我认为只是 Web API 造成了所有麻烦。在任何其他情况下,Request["name"] (就像在 PHP 中一样 :) )或在方法签名中指定参数都可以(对于 GET 和 POST)。对于 Web API,它似乎更复杂。
  • 不,不是。 actionContext.Request.GetQueryNameValuePairs() 将为您提供查询字符串中的参数,无论请求当前操作方法的动词是什么。显示您的 WebClient 代码。
  • @CodeCaster,好的,我现在已经添加了 WebClient 代码。

标签: c# asp.net-mvc asp.net-web-api asp.net-mvc-5


【解决方案1】:

使用您显示的代码,您使用 application/x-www-form-urlencoded 内容类型在请求正文中上传 param=value

如果您还想使用查询字符串,则需要使用WebClient.QueryString property单独设置:

// Query string parameters
NameValueCollection queryStringParameters = new NameValueCollection();
queryStringParameters.Add("someOtherParam", "foo");
client.QueryString = queryStringParameters;

// Request body parameters
NameValueCollection requestParameters = new NameValueCollection();
requestParameters.Add("param", param);

client.UploadValues(uri, method, requestParameters);

这将使请求转到uri?someOtherParam=foo,使您能够通过actionContext.Request.GetQueryNameValuePairs()读取服务器端的查询字符串参数。

【讨论】:

  • 有没有办法使用 Web API 中可用的方法(在服务器端)读取请求正文参数?
  • @Artem await Request.Content.ReadAsFormDataAsync(),这会给你另一个NameValueCollection
  • 感谢您的回答! :) +1
猜你喜欢
  • 2017-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-29
  • 1970-01-01
  • 1970-01-01
  • 2012-05-12
相关资源
最近更新 更多