415,原因短语:'Unsupported Media Type'

415, ReasonPhrase: 'Unsupported Media Type'

全部,

当我尝试使用 postman 调用我的网络 api (.net 6) 端点时出现以下异常(我尝试了内容类型:form-data/application/x-www-form-urlencoded 并且我做到了在正文中包含用户、密码参数,post url: http://localhost:5000/api/auth):

  {StatusCode: 415, ReasonPhrase: 'Unsupported Media Type', Version: 1.1, Content: System.Net.Http.HttpConnectionResponseContent, Headers:
{
  Date: Thu, 17 Mar 2022 18:12:40 GMT
  Server: Kestrel
  Transfer-Encoding: chunked
  Content-Type: application/problem+json; charset=utf-8
}}

这是我的网络 api 控制器:

[ApiController]
    [Route("/api/[controller]")]
    public class AuthController : ControllerBase
    {

        private readonly ILogger<AuthController> _logger;

        public AuthController(ILogger<AuthController> logger)
        {
            _logger = logger;
        }

        [HttpPost()]
        public string GetToken([FromBody] AuthCredentials cred)
        {
            _logger.LogInformation($"{nameof(AuthController)} => Received user: {cred.User}");
            _logger.LogInformation($"{nameof(AuthController)} => Received pwd: {cred.Pwd}");
            return "token:12345";
        }
    }

它以前工作过,当我将 user/pwd 作为单独的字段传递时,在我输入 [FromBody] 的那一刻它停止工作并且我开始收到此异常。

public class AuthCredentials
    {
        public string User { get; set; }
        public string Pwd { get; set; }
    }

我确实使用 SignalR + Webapis,这是我的 Startup.cs

public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers(); // only for web api controllers

            services.AddSignalR()
                .AddHubOptions<ServerHub>(options =>
                {
                    options.EnableDetailedErrors = true;
                    options.MaximumReceiveMessageSize = null; // null is unlimited
                })
                // add message pack, requires nuget: Microsoft.AspNetCore.SignalR.Protocols.MessagePack (you must be on .net6 to use this nuget)
                .AddMessagePackProtocol(); 
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Running SignalR hub, at url: /server");
                });

                endpoints.MapHub<ServerHub>("/server", options =>
                {
                    options.Transports = HttpTransportType.WebSockets;
                
                });

                endpoints.MapControllers(); // only for api controllers

            });
        }
    }

**

** 我能够通过更改此行并添加表单数据内容类型来修复不受支持的媒体类型异常:

services
                .AddControllers(options =>
                {
                    var jsonInputFormatter = options.InputFormatters
                        .OfType<Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter>()
                        .Single();
                    jsonInputFormatter.SupportedMediaTypes
                        .Add("application/x-www-form-urlencoded");
                }); 

但是现在,当我 运行 post man 我得到 400,错误的请求异常:

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "00-46970e65eec389a5d6d355d960823e57-dd8db1776ac7f90c-00",
    "errors": {
        "$": [
            "The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. Path: $ | LineNumber: 0 | BytePositionInLine: 0."
        ]
    }
}

问: 如何使用表单数据(用户、密码)传入,并在服务器上填充 AuthCredentials 对象?

如果您尝试从邮递员那里调用此操作

 [HttpPost()]
public string GetToken([FromBody] AuthCredentials cred)

 _logger.LogInformation($"{nameof(AuthController)} => Received user: {cred.User}");
 _logger.LogInformation($"{nameof(AuthController)} => Received pwd: {cred.Pwd}");
 return "token:12345";
}

您需要 select body=>raw=>json postman 中的选项并将您的数据添加为

{
  "user": "user",
  "pwd" : "pwd"
}

并删除您添加到 AddController 配置的所有额外代码。这只是令人困惑,将来可能会引起更多问题

它不起作用的原因是您试图从 URL 检索参数,但您使用的是 [FromBody],这应该是使用您的请求正文发送参数。

尝试如下所示发送您的参数