Luc*_*eis 7 c# webclient file-upload console-application asp.net-mvc-3
我正在尝试使用控制台应用程序将XML文件发送到在ASP.NET MVC 3中开发的Web应用程序,并接收另一个XML作为响应.
控制台应用程序中返回的错误是:
远程服务器返回错误:(500)内部服务器错误.
当我让Fiddler2运行时,我看到了这个错误:
你调用的对象是空的.
控制台应用程序中的代码是:
static void Main(string[] args)
{
var wc = new WebClient();
byte[] response = wc.UploadFile("http://mysite.com/Tests/Test", "POST", "teste.xml");
string s = System.Text.Encoding.ASCII.GetString(response);
Console.WriteLine(s);
Console.ReadKey();
}
Run Code Online (Sandbox Code Playgroud)
MVC控制器中的代码是:
[HttpPost]
public ActionResult Test(HttpPostedFileBase file)
{
XElement xml = XElement.Load(new System.IO.StreamReader(file.InputStream));
var test = new MyTest();
return File(test.RunTest(xml), "text/xml", "testresult.xml");
}
Run Code Online (Sandbox Code Playgroud)
RunTest()效果很好,因为这个方法在我通过表单上传文件时使用(在同名的方法中,使用方法GET).RunTest()返回带响应的XML.
当我调试MVC应用程序时,我看到了问题:变量file为null!
我该如何解决这个问题?我需要在我的控制台应用程序中更改它才能实际发送文件?或者是改变MVC方法的情况?
并且,在尝试使用之前WebClient,我在这里尝试了这个代码:http://msdn.microsoft.com/en-us/library/debx8sh9.aspx,并得到了相同的结果.
您的问题是WebClient.UploadFile没有发布一个表单,其enctype设置为multipart/form-data,使用名为"file"的输入,以便MVC映射到.尝试将服务器端方法更改为:
[HttpPost]
public ActionResult Test()
{
var file = Request.Files[0] as HttpPostedFile;
XElement xml = XElement.Load(new System.IO.StreamReader(file.InputStream));
var test = new MyTest();
return File(test.RunTest(xml), "text/xml", "testresult.xml");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5614 次 |
| 最近记录: |