Accessing query string variables sent as POST in HttpActionContext

百般思念 提交于 2020-05-27 10:42:14

问题


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

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

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?

EDIT: WebClient Code

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

    }
}

回答1:


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

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



来源:https://stackoverflow.com/questions/33201395/accessing-query-string-variables-sent-as-post-in-httpactioncontext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!