【问题标题】:415 Unsupported Media Type in ASP.NET core web api415 ASP.NET 核心 web api 中不支持的媒体类型
【发布时间】:2021-03-31 03:24:43
【问题描述】:

我正在尝试使用 asp.net core web api,所以我用这样的控制器制作了一些简单的 api:

[ApiController]
[Route("MyController")]
public class MyController : ControllerBase
{
    [HttpGet]
    [Route("GetResult")]
    public IActionResult GetResult(string param1, string param2= null, SomeClassObj obj = null)
    {  .... }
}

我在本地运行 api 并发送了这个邮递员 GET 请求:

https://localhost:5001/MyController/GetResult?param1=someString

我收到错误:415 Unsupported Media Type

我在这里缺少什么以便它可以工作?

【问题讨论】:

    标签: asp.net-core


    【解决方案1】:

    您使用的是哪个版本的 .NET Core?

    尝试从浏览器发出请求,看看是否有相同的结果。

    另外,您确定您在 Postman 中执行的是 GET 而不是 POST 请求? GET 请求不应出现 415 错误,尤其是当您不发送任何正文时。 此错误主要发生在您尝试发送正文并且没有通过Content-Type 标头指定媒体类型时。

    确保请求是 GET 并且你的 body 是空的。

    修改后的解决方案:

    当您尝试解析 DTO 对象 (SomeClassObj) 时,您应该指定值的来源。为了解决您的具体情况,请在SomeClassObj 之前添加[FromQuery] 属性。

    您的代码应如下所示:

    [ApiController]
    [Route("MyController")]
    public class MyController : ControllerBase
    {
        [HttpGet]
        [Route("GetResult")]
        public IActionResult GetResult(string param1, string param2= null, [FromQuery]SomeClassObj obj = null)
        {  .... }
    }
    

    这告诉解析器从查询字符串中获取数据。这将解决 415 问题。但是,如果您想绑定到复杂类型,尤其是在 get 上,请查看这些主题:ASP.NET CORE 3.1 Model Bindingthis issue,因为您很可能会在解析 DTO 对象时遇到问题。

    【讨论】:

    • .net 核心 3.1。在邮递员中,它是一个 GET 请求并且没有正文。当将相同的请求复制粘贴到浏览器时,我再次收到 415 错误:键入“tools.ietf.org/html/rfc7231#section-6.5.13”标题“不支持的媒体类型”状态 415 traceId“|f42c992c-498a76ef71e4af5e。”
    • @YonatanNir 你错过了一些东西。请使用您在控制器中使用的完整代码编辑您的初始帖子。另外,为了确保起见,请附上您在浏览器和邮递员中执行的请求的屏幕截图。
    • 好的,我很抱歉,因为我在这里写了一个旧代码。 GetResult 的签名有一个额外的参数,它不是字符串,它是导致它的人
    • 是的,很可能您正在尝试使用 DTO 对象。无论如何更新您的初始帖子,以便我们为您提供适当的解决方案。
    • 已编辑。你也可以编辑回复,我会接受的
    【解决方案2】:

    从 .NET MVC 调用 WEB API 后,我遇到了同样的错误。 正如@zhulien 所建议的,我已经在 WebAPI 中从 FromBody 更改为 FromForm,它对我来说很好。

    .NET Core WebAPI 方法。

    public async Task<IActionResult> Login([FromForm] LoginModel loginInfo)
        { // JWT code here }
    

    .Net Core MVC 动作方法。

    public async void InvokeLoginAPIAsync(string endPoint, string userName, string pwd)
        {
            configuration = new ConfigurationBuilder()
                  .AddJsonFile("appsettings.json")
                  .Build();
            baseUrl = configuration["Application:BaseAPI"] ?? throw new Exception("Unable to get the configuration with key Application:BaseAPI");
    
            string targetUrl = string.Format("{0}/{1}", baseUrl, endPoint);
    
            using (HttpClient deviceClient = new HttpClient())
            {
                var request = new HttpRequestMessage(HttpMethod.Post, targetUrl);
    
               var data = new List<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("userName", userName),
                    new KeyValuePair<string, string>("password", pwd)
                };
    
                request.Content = new FormUrlEncodedContent(data);
    
                using (var response = await deviceClient.SendAsync(request))
                {
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        TempData["Response"] = JsonConvert.SerializeObject(response.Content);
                    }
                }
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2019-07-28
      • 2018-08-20
      • 2016-11-26
      • 2020-01-17
      • 2020-10-06
      • 1970-01-01
      • 1970-01-01
      • 2020-09-25
      • 2014-05-10
      相关资源
      最近更新 更多