【问题标题】:Define header for upload file in API在 API 中定义上传文件的标头
【发布时间】:2021-02-03 23:32:03
【问题描述】:

我正在尝试上传 excel 文件以将其转换为 Json,但我需要通过 API 网关。我从 API Gateway 传递文件时遇到问题。

我尝试手动在ContentDispositionContentLengthContentType 中设置标题。

 using (var client = new HttpClient())
    {
        using (var Content = new MultipartFormDataContent())
        {
            var name = Path.GetFileName(postedFile.FileName);

            HttpContent content = new StringContent("");
            content.Headers.Clear();
            content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
            {
                Name = name,
                FileName = name
            };
            content.Headers.Add("Content-Length", postedFile.ContentLength.ToString());
            content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data");
            Content.Add(content);
        }

        HttpResponseMessage reply = new HttpResponseMessage();
        reply = await client.GetAsync(@"http://localhost:60897/api/ExceltoJSONConversion"); 
        if (reply.IsSuccessStatusCode)
        {
            var responseString = await reply.Content.ReadAsStringAsync();
            return Json(JsonConvert.DeserializeObject(responseString));
        }
    }

我已经尝试了几个代码,但 reply 总是返回代码 405 MethodNotAllowed。 这是我的控制器,我在其中进行文件

[HttpPost]
[Route("api/ExceltoJSONConversion")]
public IHttpActionResult ExceltoJSONConversion()
    {
       // Process the file from API Gateway
    }

我在定义 Header multipart/form-data 时是否遗漏了什么?还是我的代码一团糟?

【问题讨论】:

    标签: c# asp.net http-headers multipartform-data api-gateway


    【解决方案1】:

    您的 API 方法仅接受 POST 请求([HttpPost] 属性)。

    在您的客户端中,您正尝试通过 GET 方法(client.GetAsync ...)获取 API。

    要么使用 [HttpGet] 而不是 [HttpPost] 来装饰您的 API 方法,要么将客户端部分更改为使用 POST (client.PostAsync ...)。

    【讨论】:

      猜你喜欢
      • 2013-06-20
      • 1970-01-01
      • 1970-01-01
      • 2018-07-07
      • 2017-07-08
      • 2017-06-09
      • 2014-04-05
      • 2020-08-27
      • 1970-01-01
      相关资源
      最近更新 更多