如何为multipart/form-data设置webapi控制器

tex*_*697 47 c# multipartform-data asp.net-web-api

我想弄清楚如何完成这件事.我没有使用我的代码获得任何有用的错误消息,所以我使用其他东西来生成一些东西.我在错误消息后附加了该代码.我已经找到了一个教程,但我不知道如何用我所拥有的实现它.这就是我现在拥有的

public async Task<object> PostFile()
    {
        if (!Request.Content.IsMimeMultipartContent())
            throw new Exception();


        var provider = new MultipartMemoryStreamProvider();
        var result = new { file = new List<object>() };
        var item = new File();

        item.CompanyName = HttpContext.Current.Request.Form["companyName"];
        item.FileDate = HttpContext.Current.Request.Form["fileDate"];
        item.FileLocation = HttpContext.Current.Request.Form["fileLocation"];
        item.FilePlant = HttpContext.Current.Request.Form["filePlant"];
        item.FileTerm = HttpContext.Current.Request.Form["fileTerm"];
        item.FileType = HttpContext.Current.Request.Form["fileType"];

        var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
        var user = manager.FindById(User.Identity.GetUserId());

        item.FileUploadedBy = user.Name;
        item.FileUploadDate = DateTime.Now;

        await Request.Content.ReadAsMultipartAsync(provider)
         .ContinueWith(async (a) =>
         {
             foreach (var file in provider.Contents)
             {
                 if (file.Headers.ContentLength > 1000)
                 {
                     var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
                     var contentType = file.Headers.ContentType.ToString();
                     await file.ReadAsByteArrayAsync().ContinueWith(b => { item.FilePdf = b.Result; });
                 }


             }


         }).Unwrap();

        db.Files.Add(item);
        db.SaveChanges();
        return result;

    }
Run Code Online (Sandbox Code Playgroud)

错误

对象{message:"此资源不支持请求实体的媒体类型'multipart/form-data'.",exceptionMessage:"没有MediaTypeFormatter可用于读取具有媒体类型'multipart/form-data'的对象内容msgstr","exceptionType:"System.Net.Http.UnsupportedMediaTypeException",stackTrace:"at System.Net.Http.HttpContentExtensions.ReadAs ... atterLogger,CancellationToken cancellationToken)"} exceptionMessage:"没有MediaTypeFormatter可用于读取类型的对象"来自媒体类型'multipart/form-data'的内容的HttpPostedFileBase'."exceptionType:"System.Net.Http.UnsupportedMediaTypeException"message:"此资源不支持请求实体的媒体类型'multipart/form-data'. stackTrace:"at System.Net.Http.HttpContentExtensions.ReadAsAsync [T](HttpContent内容,类型类型,IEnumerable 1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken) ? at System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable1格式化程序,IFormatterLogger formatterLogger,CancellationToken cancellationToken)

用于生成错误消息的代码

    [HttpPost]
    public string UploadFile(HttpPostedFileBase file)
    {

        if (file.ContentLength > 0)
        {
            var fileName = Path.GetFileName(file.FileName);
            var path = Path.Combine(HttpContext.Current.Server.MapPath("~/uploads"), fileName);
            file.SaveAs(path);


        }
        return "/uploads/" + file.FileName;
    }
Run Code Online (Sandbox Code Playgroud)

public class File
{
    public int FileId { get; set; }
    public string FileType { get; set; }
    public string FileDate { get; set; }
    public byte[] FilePdf { get; set; }
    public string FileLocation { get; set; }
    public string FilePlant { get; set; }
    public string FileTerm { get; set; }
    public DateTime? FileUploadDate { get; set; }
    public string FileUploadedBy { get; set; }

    public string CompanyName { get; set; }
    public virtual ApplicationUser User { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

Tho*_*ena 75

我通常只在Mvc控制器中使用HttpPostedFileBase参数.处理ApiControllers时,尝试检查传入文件的HttpContext.Current.Request.Files属性:

[HttpPost]
public string UploadFile()
{
    var file = HttpContext.Current.Request.Files.Count > 0 ?
        HttpContext.Current.Request.Files[0] : null;

    if (file != null && file.ContentLength > 0)
    {
        var fileName = Path.GetFileName(file.FileName);

        var path = Path.Combine(
            HttpContext.Current.Server.MapPath("~/uploads"),
            fileName
        );

        file.SaveAs(path);
    }

    return file != null ? "/uploads/" + file.FileName : null;
}
Run Code Online (Sandbox Code Playgroud)


Nic*_*zee 57

这就解决了我的问题.
将以下行添加到WebApiConfig.cs

config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data"));
Run Code Online (Sandbox Code Playgroud)

  • 这只会使 ASP.NET 将“multipart/form-data”请求路由到您的控制器。它无法反序列化表单值并将它们绑定到方法的参数,因为“XmlFormatter”无法解析“multipart/form-data”有效负载。 (2认同)

Dak*_*ada 14

你可以使用这样的东西

[HttpPost]
public async Task<HttpResponseMessage> AddFile()
{
    if (!Request.Content.IsMimeMultipartContent())
    {
        this.Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
    }

    string root = HttpContext.Current.Server.MapPath("~/temp/uploads");
    var provider = new MultipartFormDataStreamProvider(root);
    var result = await Request.Content.ReadAsMultipartAsync(provider);

    foreach (var key in provider.FormData.AllKeys)
    {
        foreach (var val in provider.FormData.GetValues(key))
        {
            if (key == "companyName")
            {
                var companyName = val;
            }
        }
    }

    // On upload, files are given a generic name like "BodyPart_26d6abe1-3ae1-416a-9429-b35f15e6e5d5"
    // so this is how you can get the original file name
    var originalFileName = GetDeserializedFileName(result.FileData.First());

    var uploadedFileInfo = new FileInfo(result.FileData.First().LocalFileName);
    string path = result.FileData.First().LocalFileName;

    //Do whatever you want to do with your file here

    return this.Request.CreateResponse(HttpStatusCode.OK, originalFileName );
}

private string GetDeserializedFileName(MultipartFileData fileData)
{
    var fileName = GetFileName(fileData);
    return JsonConvert.DeserializeObject(fileName).ToString();
}

public string GetFileName(MultipartFileData fileData)
{
    return fileData.Headers.ContentDisposition.FileName;
}
Run Code Online (Sandbox Code Playgroud)


Red*_*ane 9

也许聚会迟到了。但是有一个替代解决方案是使用ApiMultipartFormFormatter插件。

此插件可帮助您像 ASP.NET Core 一样接收 multipart/formdata 内容。

在github页面中,已经提供了demo。


Ric*_*ard 8

5 年后,.NET Core 3.1 允许您像这样指定媒体类型:

[HttpPost]
[Consumes("multipart/form-data")]
public IActionResult UploadLogo()
{
    return Ok();
}
Run Code Online (Sandbox Code Playgroud)

  • @GyumFox 不是真的,我现在正在 .NET 5 中进行测试并因此被阻止。 (3认同)