开发者

Access post data directly

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 p开发者_如何学Carse the parameters.

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

This is potentially a very simple question!

Thanks


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


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


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


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜