c# - 访问在 HttpActionContext 中作为 POST 发送的查询字符串变量

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

我正在尝试访问使用 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/

相关文章:

asp.net-mvc - 安装 MVC3 后,我无法在 Visual Studio 2010 上创建或打开 MVC2 项目

c# - 为什么我无法调用 DbContextOptionsBuilder 上的 UseInMemoryDatabase 方法?

c# - NHibernate - 无法执行查询

c# - 如何为 ListBoxItem 创建标题?

c# - Unity3D - Android 通信?

javascript - 为什么这是未定义的以及如何解决这个问题? C#

c# - 如何更改 C# winforms 中未使用空间选项卡的背景颜色?

c# - 使用新值更新现有对象

c# - ASP.NET WEBAPI c# 在删除时给出 404

c# - 身份验证 token 提供者 : Custom error message