如何在 ASP.NET Core Web API 控制器中接收字节数组和 header 内容

How to receive a byte array and header content in a ASP.NET Core Web API Controller

我需要在 c# ASP.NET Core Web API 应用程序中接收内容和字节数组。

**--HttpClient (console Application)**  

                Dictionary<int, byte[]> fileparts = new Dictionary<int, byte[]>();
                int bufferSize = 1000 * 1024;

                byte[] buffer;
                string filePath = @"D:\Extra\Songs\test.mp3";
                using (FileStream fileData = File.OpenRead(filePath))
                {
                    int index = 0;
                    int i = 1;
                    while (fileData.Position < fileData.Length)
                    {

                        if (index + bufferSize > fileData.Length)
                        {
                            buffer = new byte[(int)fileData.Length - index];
                            fileData.Read(buffer, 0, ((int)fileData.Length - index));
                        }
                        else
                        {
                            buffer = new byte[bufferSize];
                            fileData.Read(buffer, 0, bufferSize);
                        }

                        fileparts.Add(i, buffer);
                        index = (int)fileData.Position;
                        i++;
                    }
                }
                
 while (fileparts.Count() != 0)
 {               
      var data = fileparts.First();          
  var fileContent = new ByteArrayContent(data);//byte content
    fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "test" };
                        fileContent.Headers.Add("id", id);
                        fileContent.Headers.Add("name", name);
                        fileContent.Headers.Add("length", length);
                        if (fileparts.Count() == 1)
                          fileContent.Headers.Add("IsCompleted", "true");
                        else
                          fileContent.Headers.Add("IsCompleted", "false");
                          
                    using (var content = new MultipartFormDataContent())
                    {
                       content.Add(fileContent);
                       // Make a call to Web API 
                        var result = client.PostAsync("/api/file", fileContent).Result;
                        if (result.StatusCode == System.Net.HttpStatusCode.OK)
                            fileparts.Remove(data.Key);
                    }

**--WebApi Core ApiController**

    public class FileController : Controller
    {
        [HttpPost]
        public async Task<IActionResult> Post()
        {
    /*i need to get the content here , for some reason existing .NET libraries does not work here
    like 
        MultipartMemoryStreamProvider provider = new MultipartMemoryStreamProvider();
        FilePart part = null;
       
        await Request.Content.ReadAsMultipartAsync(provider); -- request.content not available 
        using (Stream fileStream = await provider.Contents[0].ReadAsStreamAsync())
                {
                    part = provider.Contents[0].Headers.GetData(); //public static FilePart GetData name,length,id 
                    part.Data = fileStream.ReadFully();
    */    
    }
后端我正在工作,但找不到新的 asp.net 核心控制器解析文件对象和来自客户端 post 的数据到服务的方法!任何想法将一如既往地不胜感激......

您可以修改您的控制器操作方法,如下所示,以根据需要接受 ByteArrayContentMultipartFormDataContent。我在 POST.

中为模型绑定使用了 [FromBody] 属性

这里是关于 [FromBody]

的更多信息

https://docs.microsoft.com/en-us/aspnet/core/mvc/models/model-binding

public class FileController : Controller
    {
        [HttpPost]
        public async Task<IActionResult> Post([FromBody] MultipartFormDataContent content)
        {
         MultipartMemoryStreamProvider provider = new MultipartMemoryStreamProvider();
        FilePart part = null;
         // access the content here 
         await content.ReadAsMultipartAsync(provider);
        // rest of the code
       }
   }

如前所述,您应该使用 content 到 post 到 API,如下所示

var result = client.PostAsync("/api/file", content).Result;

我过去成功地使用过这个:

[HttpPost]
public async Task<IActionResult> Post(IFormFile formFile)
{
    using (Stream stream = formFile.OpenReadStream())
    {
         //Perform necessary actions with file stream
    }
}

我相信您还需要更改客户端代码以匹配参数名称:

fileContent.Headers.Add("name", "formFile");