我正在尝试访问使用 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);
}
}
最佳答案
使用您显示的代码,您上传 param=value
在请求正文中使用 application/x-www-form-urlencoded
内容类型。
如果您还想使用查询字符串,则需要使用 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()
读取服务器端的查询字符串参数.
关于c# - 访问在 HttpActionContext 中作为 POST 发送的查询字符串变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33201395/