gpt4 book ai didi

c# - 是否可以在带有上传文件的 asp.net web api 中进行模型绑定(bind)?

转载 作者:行者123 更新时间:2023-12-04 04:18:14 24 4
gpt4 key购买 nike

该模型:

public class UploadFileModel
{
public int Id { get; set; }
public string FileName { get; set; }
public HttpPostedFileBase File { get; set; }
}

Controller :
public void Post(UploadFileModel model)
{
// never arrives...
}

我收到一个错误

"No MediaTypeFormatter is available to read an object of type 'UploadFileModel' from content with media type 'multipart/form-data'."



有没有办法解决?

最佳答案

这不容易。 Web API 中的模型绑定(bind)与 MVC 中的模型绑定(bind)根本不同,您必须编写一个 MediaTypeFormatter 来将文件流读入您的模型并另外绑定(bind)原语,这可能会非常具有挑战性。

最简单的解决方案是使用某种类型的 MultipartStreamProvider 从请求中获取文件流。其他参数使用 FormData该提供者的名称值集合

示例 - http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-2 :

public async Task<HttpResponseMessage> PostFormData()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}

string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);

try
{
await Request.Content.ReadAsMultipartAsync(provider);

// Show all the key-value pairs.
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in provider.FormData.GetValues(key))
{
Trace.WriteLine(string.Format("{0}: {1}", key, val));
}
}

return Request.CreateResponse(HttpStatusCode.OK);
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}

关于c# - 是否可以在带有上传文件的 asp.net web api 中进行模型绑定(bind)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12901905/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com