Access post data directly

asp.net Mvc

asp.net Mvc Problem Overview


I have an action in one of my controllers that is going to receive HTTP POST requests from outside of my MVC website.

All these POST requests will have the same parameters and I need to be able to parse the parameters.

How can I access the post data from within the action?

This is potentially a very simple question!

Thanks

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

The POST data from your HTTP Reques can be obtained at Request.Form.

Solution 2 - asp.net Mvc

string data = new System.IO.StreamReader(Request.InputStream).ReadToEnd(); 

Solution 3 - asp.net Mvc

Use

Request.InputStream 

This will give you raw access to the body of the HTTP message, which will contain all the POST variables.

http://msdn.microsoft.com/en-us/library/system.web.httprequest.inputstream.aspx

Solution 4 - asp.net Mvc

I was trying to access the POST data after I was inside of the MVC controller. The InputStream was already parsed by the controller so I needed to reset the position of the InputStream to 0 in order to read it again.

This code worked for me...

 HttpContext.Current.Request.InputStream.Position = 0;
 var result = new System.IO.StreamReader(HttpContext.Current.Request.InputStream).ReadToEnd();

Solution 5 - asp.net Mvc

Stream req = Request.InputStream;
            req.Seek(0, System.IO.SeekOrigin.Begin);
            string json = new StreamReader(req).ReadToEnd();

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            dynamic items = serializer.Deserialize<object>(json);
            string id = items["id"];
            string image = items["image"];

///you can access paramters by name or index

Solution 6 - asp.net Mvc

The web server shouldn't care where the request is coming from. If your client application has a input control called username and it posts to your application it will pick up the same as if your posted if from your own application with an input called username.

One huge caveat is if you have implemented AntiForgeryValidation which will cause a big headache to allow an outside form to post.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndrewCView Question on Stackoverflow
Solution 1 - asp.net MvcJim BollaView Answer on Stackoverflow
Solution 2 - asp.net MvcBrady MoritzView Answer on Stackoverflow
Solution 3 - asp.net MvcTomas McGuinnessView Answer on Stackoverflow
Solution 4 - asp.net MvcTWillyView Answer on Stackoverflow
Solution 5 - asp.net MvcMahmoud AbdallahView Answer on Stackoverflow
Solution 6 - asp.net MvcMichael GattusoView Answer on Stackoverflow