访问HttpActionContext中作为POST发送的查询字符串变量 [英] Accessing query string variables sent as POST in HttpActionContext

查看:713
本文介绍了访问HttpActionContext中作为POST发送的查询字符串变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to access a query string parameter that was sent using the POST method (WebClient) to the Web API in ASP.NET MVC 5 (in an overridden AuthorizationFilterAttribute).

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

For Get, I've used the following trick: var param= actionContext.Request.GetQueryNameValuePairs().SingleOrDefault(x => x.Key.Equals("param")).Value;

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

However, once I use POST, this does work and the variable paran is set to null. I think that's because the query string method only applies to the url, not the body. Is there any way to get the query string (using one method preferably) for both GET and POST requests?

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);

    }
}

推荐答案

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

Using the code you show, you upload the param=value in the request body using the application/x-www-form-urlencoded content-type.

如果您还想利用查询字符串,则需要使用

If you also want to utilize the query string, you need to set it separately using the 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()在服务器端读取查询字符串参数.

This will make the request go to uri?someOtherParam=foo, enabling you to read the query string parameters serverside through actionContext.Request.GetQueryNameValuePairs().

这篇关于访问HttpActionContext中作为POST发送的查询字符串变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆