代码之家  ›  专栏  ›  技术社区  ›  Lakmal

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

  •  1
  • Lakmal  · 技术社区  · 8 年前

    我需要在c#ASP中接收内容和字节数组。NET核心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();
        */    
        }
    2 回复  |  直到 8 年前
        1
  •  3
  •   Niladri    8 年前

    您可以修改控制器操作方法,如下所示,以接受 ByteArrayContent MultipartFormDataContent 根据需要。我用过 [FromBody] POST中模型绑定的属性。

    [来自正文]

    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 如下所示发布到此API

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

        2
  •  2
  •   alec    8 年前

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

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

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