Receiving a HTTP POST in HTTP Handler?

时光怂恿深爱的人放手 提交于 2019-12-18 15:24:06

问题


I need to listen and process a HTTP POST string in a HTTP handler.

Below is the code for posting the string to handler -

string test = "charset = UTF-8 & param1 = val1 & param2 = val2 & param3 = val3 & param4 = val4;
byte[] data = Encoding.UTF8.GetBytes(test);
PostData("http://localhost:53117/Handler.ashx", data);

What I tried in Handler is -

    public void ProcessRequest(HttpContext context)
    {
        var value1 = context.Request["param1"];
    }

But its null. How can I listen and get the parameter values in Handler?


回答1:


You don't seem to be using any of the standard request encodings, instead you seem to be reinventing some custom protocol, so you cannot rely on the server ASP.NET to be able to parse this request. You will have to read the values directly from the InputStream:

public void ProcessRequest(HttpContext context)
{
    using (var reader = new StreamReader(context.Request.InputStream))
    {
        // This will equal to "charset = UTF-8 & param1 = val1 & param2 = val2 & param3 = val3 & param4 = val4"
        string values = reader.ReadToEnd();
    }
}

If on the other hand you use some standard request encoding such as application/x-www-form-urlencoded you will be able to read the parameters as usual.

Here's how such a request payload might look like:

POST /Handler.ashx HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 47
Connection: close

param1=val1&param2=val2&param3=val3&param4=val4

In order to send such a request you could use a WebClient:

using (var client = new WebClient())
{
    var values = new NameValueCollection
    {
        { "param1", "value1" },
        { "param2", "value2" },
        { "param3", "value3" },
        { "param4", "value4" },
    };
    byte[] result = client.UploadValues(values);
}

Now on the server you can read the values like that:

public void ProcessRequest(HttpContext context)
{
    var value1 = context.Request["param1"];
    var value2 = context.Request["param2"];
    ...
}



回答2:


Change

    var value1 = context.Request["param1"];

to

    var value1 = context.Request.Form["param1"];



回答3:


It's actually :

    context.Request.Params["param1"];


来源:https://stackoverflow.com/questions/16996713/receiving-a-http-post-in-http-handler

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