4

I have a controller that looks like this for importing xml to my site:

 [HttpPost] public ActionResult Import(string xml) { 

I have a standalone application that reads an xml file and sends it to the url. It looks like this:

 static void Main(string[] args) { var reader = new StreamReader(@"myfile.xml"); var request = WebRequest.Create("http://localhost:41379/mycontroller/import"); request.Method = "POST"; request.ContentType = "text/xml"; StreamWriter sw = new StreamWriter(request.GetRequestStream()); sw.Write(reader.ReadToEnd()); sw.Close(); var theResponse = (HttpWebResponse)request.GetResponse(); StreamReader sr = new StreamReader(theResponse.GetResponseStream()); var response = sr.ReadToEnd(); } 

The controller gets called properly, but when I break in there, the argument is null. I am pretty sure I am just not setting the right content type or something like that. What is the proper way to encode the xml so that the framework will get it and give it to the controller properly?

5
  • Where are you passing the xml content to the action? Commented Jun 16, 2011 at 22:39
  • I am writing it to the request stream. Commented Jun 16, 2011 at 22:42
  • but you are not giving it a name. It needs to be a formal named HTTP POST param. Commented Jun 16, 2011 at 23:02
  • you are also missing a lot of using statements there for your streams and requests Commented Jun 16, 2011 at 23:31
  • @crice, yes, but that is the entire program, so they'll get disposed anyway. @kirk, thats kinda what I'm asking how to do. Commented Jun 17, 2011 at 0:04

1 Answer 1

4

Save yourself a lot of grief and use WebClient.UploadFile.

Having led you the wrong way, I wrote a controller and client that seem to work fine:

Controller

public class HomeController : Controller { public ActionResult Upload() { XDocument doc; using (var sr = new StreamReader(Request.InputStream)) { doc = XDocument.Load(sr); } return Content(doc.ToString()); } } 

client

static void Main(string[] args) { var req = (HttpWebRequest)WebRequest.Create("http://host/Home/Upload"); req.Method = "POST"; req.ContentType = "text/xml"; using (var stream = File.OpenRead("myfile.xml")) using (var requestStream = req.GetRequestStream()) { stream.CopyTo(requestStream); } using (var response = (HttpWebResponse) req.GetResponse()) using (var responseStream = response.GetResponseStream()) using (var sr = new StreamReader(responseStream)) { XDocument doc = XDocument.Load(sr); Console.WriteLine(doc); } Console.ReadKey(); } 
Sign up to request clarification or add additional context in comments.

1 Comment

good point. I can just read the input stream. I don't really need the framework to parse it out for me at all. I'll try this soon.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.