简体   繁体   English

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

[英]How to send json data and formdata (files) from Angular to an ASP.NET WebAPI Controller action in one shot?

Let's say I have an ASP.NET WebAPI Controller that looks like that: 假设我有一个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)
    {
        // ...
    }
}

Is there anyway I can send / upload / post from an Angular app (obviously in a service with HttpClient properly injected) a model (which is the json data that would be extracted from the body) and the form data containing files...)? 无论如何我可以从Angular应用程序发送/上传/发布(显然是在正确注入HttpClient的服务中)模型(这是从主体中提取的json数据)和包含文件的表单数据......) ?

The problem is... I don't really see how: 问题是......我真的不知道如何:

const formData = new FormData();

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

It's like whether...: 这就像......:

  • I add the json data as part of the form data and cannot have it extracted from body as "such" in the Web API Controller action, and I have to keep the key used in the Angular app for json data and then loop over the remaining keys (which are supposedly all files). 我将json数据添加为表单数据的一部分,并且不能在Web API控制器操作中将其从body中提取为“this”,并且我必须保留Angular应用程序中用于json数据的密钥,然后循环其余部分键(可能是所有文件)。
  • I have to send a different "POST" for each file 我必须为每个文件发送一个不同的“POST”

Send a MIME multipart request ( multipart/form-data ), each blob is its own FormData entry: https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects - on the server-side you can extract different parts from the request in ASP.NET by using the Request.Content.ReadAsMultipartAsync API: https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/sending-html-form-data-part-2 发送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-形数据部-2-

You will need to change your Controller Actions to not use method parameters but to read from Request directly: 您需要更改控制器操作以不使用方法参数,而是直接从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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将数据从一个控制器动作传递到ASP.Net MVC 5中的另一个控制器动作 - pass data from one controller action to another controller action in ASP.Net MVC 5 如何将zip文件发送到ASP.NET WebApi - How to send zip files to ASP.NET WebApi 如何在angular6和ASP.NET Core 2 WebAPI中使用TypeScript模型发布FormData - How to post formData with typescript model in angular6 and asp.net core 2 webapi 如何在没有 Z9E0DA8438E1E38A1C30F4B76CE7 核心的情况下将 Json 数据从 controller 发送到 javascript? - How to send Json Data from controller to javascript without in ASP.NET Core? 如何从ASP.Net MVC控制器发布JSON数据? - How to post JSON data from ASP.Net MVC controller? 如何在不使用JS FormData的情况下将文件上传到ASP.NET MVC控制器操作 - How to upload a file to an ASP.NET MVC controller action without using JS FormData ASP.NET MVC-如何在Webapi控制器返回的Razor视图中显示数据 - ASP.NET MVC - How to display data in Razor view returned from Webapi controller ASP.NET MVC将JSON数据发送到Controller Action - ASP.NET MVC sending JSON data to a Controller Action ASP.Net MVC WebAPI - 如何在视图中显示 json 数据 - ASP.Net MVC WebAPI - How to display json data in View 在 ASP.NET MVC 中执行控制器后如何将数据发送到操作过滤器? - How Can I Send Data to the Action Filter after Execution of the controller in ASP.NET MVC?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM