将包含文件的模型从MVC站点发送到Web Api站点 [英] Sending a model containing files from an MVC site to a Web Api site
问题描述
我有一个ASP.Net MVC网站,允许用户提交表格以及上传文件.
I have an ASP.Net MVC site that allows the user to subtmit a form along with uploading files.
这部分有效.但是在我的MVC Post方法中,我需要调用ASP.Net Web API方法并将其传递给模型.
This part works. But in my MVC Post method, I need to call an ASP.Net Web API method and pass it the model.
这是我不知道该怎么做的部分.
This is the part I don't know how to do.
这是我的MVC应用程序中的模型:
Here is my model in my MVC App:
public class MyModel
{
public DateTime SubmittedDate { get; set; }
public string Comments { get; set; }
public IEnumerable<HttpPostedFileBase> Files { get; set; }
}
在我的MVC网站中,我有以下方法:
In my MVC site I have the following method:
[HttpPost]
public async Task<ActionResult> Details(MyModel model)
{
if (!ModelState.IsValid)
// the rest of the method
}
使用这种方法可以正确填充文件和模型.当我放置一个断点并浏览Files属性时,我可以看到具有正确名称和文件类型的正确数量的文件.
In this method the files and model are correctly populated. When I put a breakpoint and navigate over the Files property I can see the correct number of files with the correct names and file types.
在我的Details方法中,我想在另一个站点(即Web API站点)上调用一个方法.
In my Details method, I want to call a method on another site which is a Web API site.
这是Web API网站上的方法:
Here is the method on the Web API site:
[HttpPost]
public HttpResponseMessage Foo(MyModel myModel)
{
// do stuff
}
通常,在我的MVC方法中,我会使用PostAsJsonAsync
方法使用HttpClient
类来调用Web API.
Normally in my MVC method I would call the Web API using the HttpClient
class using the PostAsJsonAsync
method.
但是当我这样做时:
HttpResponseMessage response = await httpClient.PostAsJsonAsync(urlServiceCall, myModel);
我收到此错误:
Newtonsoft.Json.JsonSerializationException
Newtonsoft.Json.JsonSerializationException
其他信息:从"ReadTimeout"获取值时出错 "System.Web.HttpInputStream".
Additional information: Error getting value from 'ReadTimeout' on 'System.Web.HttpInputStream'.
推荐答案
这是因为它试图序列化文件的输入流.我建议为流将其作为字节数组的Web API创建一个新模型.
That is because it is trying to serialize the input stream of the files. I would suggest creating a new model for the web api that have the stream as byte arrays.
public class PostedFile {
public int ContentLength { get; set; }
public string ContentType { get; set; }
public string FileName { get; set; }
public byte[] Data { get; set; }
}
public class WebApiModel {
public DateTime SubmittedDate { get; set; }
public string Comments { get; set; }
public List<PostedFile> Files { get; set; }
}
与流相比,序列化程序对数组的处理会更好.
the serializer would do better with the arrays than the stream.
这篇关于将包含文件的模型从MVC站点发送到Web Api站点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!