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

问题描述 投票:1回答:1

假设我有一个ASP.NET WebAPI控制器,它看起来像这样:

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应用程序发送/上传/发布(显然是在正确注入HttpClient的服务中)模型(这是从主体中提取的json数据)和包含文件的表单数据......) ?

问题是......我真的不知道如何:

const formData = new FormData();

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

这就像......:

  • 我将json数据添加为表单数据的一部分,并且不能在Web API控制器操作中将其从body中提取为“this”,并且我必须保留Angular应用程序中用于json数据的密钥,然后循环其余部分键(可能是所有文件)。
  • 我必须为每个文件发送一个不同的“POST”
c# json angular asp.net-web-api multipartform-data
1个回答
3
投票

发送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://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/sending-html-form-data-part-2

您需要更改控制器操作以不使用方法参数,而是直接从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);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.