c# - 如何为 multipart/form-data 设置 Web API Controller

标签 c# asp.net-web-api multipartform-data

我正在尝试解决这个问题。我的代码没有收到任何有用的错误消息,所以我使用了其他东西来生成一些东西。我在错误消息后附加了该代码。我找到了 tutorial在上面,但我不知道如何用我所拥有的来实现它。这是我目前拥有的:

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;

    }

错误:

Object {message: "The request entity's media type 'multipart/form-data' is not supported for this resource.", exceptionMessage: "No MediaTypeFormatter is available to read an obje…om content with media type 'multipart/form-data'.", exceptionType: "System.Net.Http.UnsupportedMediaTypeException", stackTrace: " at System.Net.Http.HttpContentExtensions.ReadAs…atterLogger, CancellationToken cancellationToken)"}exceptionMessage: "No MediaTypeFormatter is available to read an object of type 'HttpPostedFileBase' from content with media type 'multipart/form-data'."exceptionType: "System.Net.Http.UnsupportedMediaTypeException"message: "The request entity's media type 'multipart/form-data' is not supported for this resource."stackTrace: " at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken) ↵ at System.Net.Http.HttpContentExtensions.ReadAsAsync(HttpContent content, Type type, IEnumerable1 formatters, 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;
    }

类:

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; }
}

最佳答案

我通常只在 Mvc Controllers 中使用 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;
}

关于c# - 如何为 multipart/form-data 设置 Web API Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28369529/

相关文章:

asp.net-web-api - 为什么 web api(RestFul) .Net Core 服务不接受参数中的正斜杠,如何解决此问题

visual-studio-2010 - 只读模型属性未在 Web API 中序列化

javascript - 发送多部分发布请求时出现问题

java - 如何在 rest api jersey 中获取文件的大小

c# - 如何从 JsonTextReader 中获取详细的位置信息

c# 2 对于每个循环,如果一个循环有效,则另一个循环无效

c# - MVVM 数据网格绑定(bind)

c# - 工厂和 C#

asp.net - 在 Asp.Net Web API 中禁用默认验证

java - Apache Camel 多部分路线