Reputation: 23078
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?
Upvotes: 4
Views: 1913
Reputation: 120450
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();
}
Upvotes: 4