415 ASP.NET core Web api 中不支持的媒体类型

Yon*_*Nir 3 asp.net-core

我正在尝试使用 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)
    {  .... }
}
Run Code Online (Sandbox Code Playgroud)

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

https://localhost:5001/MyController/GetResult?param1=someString
Run Code Online (Sandbox Code Playgroud)

我收到错误:415 不支持的媒体类型

我在这里缺少什么才能让它发挥作用?

小智 9

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

.NET Core WebAPI 方法。

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

.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);
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)


zhu*_*ien 7

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

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

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

确保请求是 GET 并且您的正文为空。

帖子编辑后的解决方案:

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

您的代码应如下所示:

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

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