Ali Kazmi
Ali Kazmi

Reputation: 3660

How to POST data to ASP.NET HttpHandler?

I am trying to send a large chunk of data over to a HTTP handler. I can't send it using GET because of the URL length limit so I decided to POST it instead. The problem is that I can't get at the values. context.Request.Form shows that it has 0 items. So is there a way that I can POST data to a HttpHandler?

Upvotes: 15

Views: 30225

Answers (6)

Andriy F.
Andriy F.

Reputation: 2537

POST fields are contained in

HttpContext.Request.Params

To retrieve them you can use

var field = HttpContext.Request.Params["fieldName"];

Upvotes: 1

Rajesh Rao
Rajesh Rao

Reputation: 11

Faced similar problem. After correcting all issues, there was one more thing I missed in web.config - to change verb as * OR GET,POST. After that everything worked fine.

<httpHandlers>
    ...
    <add verb="*" path="test.ashx" type="Handlers.TestHandler"/>
</httpHandlers>

Upvotes: 1

splattne
splattne

Reputation: 104040

I also had the same problem. It was an client/AJAX problem. I had to set the AJAX call request header "ContentType" to

application/x-www-form-urlencoded

to make it work.

Upvotes: 4

Jaime Gomez
Jaime Gomez

Reputation: 7067

I was having the same problem, and eventually figured out that setting the content type as "json" was the issue...

contentType: "application/json; charset=utf-8"

That's a line some popular tutorials suggest you to add in the $ajax call, and works well with ASPx WebServices, but for some reason it doesn't for an HttpHandler using POST.

Hard to catch since values in the query string work fine (another technique seen in the web, though it doesn't makes much sense to use POST for that).

Upvotes: 3

Dan Herbert
Dan Herbert

Reputation: 103407

Having some code to look at would help diagnose the issue. Have you tried something like this?

jQuery code:

$.post('test.ashx', 
       {key1: 'value1', key2: 'value2'}, 
       function(){alert('Complete!');});

Then in your ProcessRequest() method, you should be able to do:

string key1 = context.Request.Form["key1"]; 

You can also check the request type in the ProcessRequest() method to debug the issue.

if(context.Request.RequestType == "POST")
{
    // Request should have been sent successfully
}
else
{
    // Request was sent incorrectly somehow
}

Upvotes: 11

Kirtan
Kirtan

Reputation: 21695

The POST data that you are sending to your HTTP Handler must be in querystring format a=b&c=d. And you can retrieve it on the server-side using Request["a"] (will return b), and so on.

Upvotes: 1

Related Questions