Getting HTTP POST in an HTTP handler?

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

Below is the code to send the string to the 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 value is zero. How can I listen and get parameter values โ€‹โ€‹in a handler?

+8
source share
3 answers

It seems you are not using any standard request encodings, instead you seem to be inventing some kind of user protocol, therefore you cannot rely on the ASP.NET server to parse this request. You will need 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 standard request encoding, such as application/x-www-form-urlencoded , you can read the parameters as usual.

Here is what the request payload looks 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 

To send such a request, you can use 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 following values:

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

In fact:

  context.Request.Params["param1"]; 
+3
source

Change

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

to

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

All Articles