在API中定义上传文件的标头

问题描述

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

我尝试在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时我缺少什么吗?还是我的代码一团糟?

解决方法

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

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

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