c# - 如何一次性将 json 数据和 formdata(文件)从 Angular 发送到 ASP.NET WebAPI Controller 操作?

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

假设我有一个如下所示的 ASP.NET WebAPI Controller :

public class StuffController
{
    [HttpGet]
    [Route("api/v1/stuff/{id:int}")]
    [ResponseType(typeof(Model))]
    public async Task<IHttpActionResult> GetAsync(int id)
    {
        // ...
    }

    [HttpPut]
    [Route("api/v1/stuff/{id:int}")]
    [ResponseType(typeof(IHttpActionResult))]
    public async Task<IHttpActionResult> UpdateAsync(int id, Model model)
    {
        // ...
    }

    [HttpPost]
    [Route("api/v1/stuff")]
    [ResponseType(typeof(IHttpActionResult))]
    public async Task<IHttpActionResult> CreateAsync([FromBody] Model model)
    {
        // ...
    }
}

无论如何,我可以从 Angular 应用程序(显然在正确注入(inject) HttpClient 的服务中)发送/上传/发布模型(将从正文中提取的 json 数据)和包含文件的表单数据。 ..)?

问题是......我真的不明白如何:

const formData = new FormData();

const uploadReq = new HttpRequest('POST', url, formData, {
     reportProgress: true,
     headers: headers
});

这就像是否...:

  • 我将 json 数据添加为表单数据的一部分,并且无法在 Web API Controller 操作中将其从正文中提取出来,并且我必须保留 Angular 应用程序中用于 json 数据的 key ,然后循环剩余的 key (据说是所有文件)。
  • 我必须为每个文件发送不同的“POST”

最佳答案

发送 MIME 多部分请求 (multipart/form-data),每个 blob 都是其自己的 FormData 条目:https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects - 在服务器端,您可以使用 Request.Content.ReadAsMultipartAsync API 从 ASP.NET 中的请求中提取不同部分:https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/sending-html-form-data-part-2

您需要将 Controller 操作更改为不使用方法参数,而是直接从 Request 读取:

public async Task<HttpResponseMessage> PostFormData()
{
    // Check if the request contains multipart/form-data.
    if( !this.Request.Content.IsMimeMultipartContent() )
    {
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
    }

    // Temporarily write the request to disk (if you use `MultipartMemoryStreamProvider` your risk crashing your server if a malicious user uploads a 2GB+ sized request)
    String root = this.Server.MapPath("~/App_Data");
    MultipartStreamProvider provider = new MultipartFormDataStreamProvider(root);

    try
    {
        // Read the form data and serialize it to disk for reading immediately afterwards:
        await this.Request.Content.ReadAsMultipartAsync( provider );

        // This illustrates how to get the names each part, but remember these are not necessarily files: they could be form fields, JSON blobs, etc
        foreach( MultipartFileData file in provider.FileData )
        {
            Trace.WriteLine( file.Headers.ContentDisposition.FileName );
            Trace.WriteLine( "Server file path: " + file.LocalFileName );
        }

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

关于c# - 如何一次性将 json 数据和 formdata(文件)从 Angular 发送到 ASP.NET WebAPI Controller 操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52123945/

相关文章:

C# FileSystemWatcher,如何知道文件是否完全复制到监视文件夹中

javascript - 如何使用 JQUERY 从 JSON 数组对象获取数据?

c# - 我的 lambda 表达式有什么问题

python - 如何在 Python 中美化 JSON?

javascript - 我的回调函数似乎没有填充我的数组?

angular - 如何从 API 响应接收类型为 csv 的文件

Angular - 如何在组件被销毁后从 <head> 中删除 &lt;style&gt; 元素

angular - "Uncaught Error: Zone already loaded." karma 测试期间

c# - 使用 TargetFramework 创建 Razor 类库到 .net core 3 会引发错误

c# - 在 ASP.NET C# 中使用不同的参数动态调用另一个 ASP 页面