zoukankan      html  css  js  c++  java
  • .Net 两个Api 服务间的文件传递

    两个服务间想传递文件数据,需要使用  MultipartFormDataContent 来模拟表单提交。其他形式基本都是 415 错误码,例如直接传递StreamContent。

    Client Code

     public async Task ClientUpload(){
                var handler = new HttpClientHandler();
                handler.ServerCertificateCustomValidationCallback = delegate { return true; };
    
                HttpClient httpClient = new HttpClient(handler);
                var m = new MultipartFormDataContent();
                var file=new FileInfo("test-File.json");
                m.Add(new StreamContent(file.OpenRead()), name: "test", fileName: file.Name); // 这里的name需要和service 函数的参数名一致,否则无法参数获取
                httpClient.BaseAddress = new Uri("service-host-url");
                var response = await httpClient.PostAsync("/file/ServiceUpload", m);
                var content = await response.Content.ReadAsStringAsync();
            }

    Service Code

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Runtime.InteropServices.ComTypes;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Logging;
    
    namespace Service.Controllers
    {
        [Route("[controller]")]
        public class FileController : ControllerBase
        {
            [HttpPost("ServiceUpload")]
            public int Upload( Microsoft.AspNetCore.Http.IFormFile file)
            {
                var fileName = file.FileName;
                return 1;
            }
        }
    }
  • 相关阅读:
    20210420
    20210419
    2021041601
    20210416
    20210415
    20210414
    20210413
    20210412
    20210409
    20210405
  • 原文地址:https://www.cnblogs.com/zhihang/p/13737342.html
Copyright © 2011-2022 走看看