.NET 5 Blazor 服务器应用对象结果"Accept"标头未被考虑



我正在.NET 5 Blazor Server应用程序中创建一个控制器,并且我从控制器返回的OkObjectResult总是返回JSON,即使我设置了Accepts: application/xml

由于在我的自定义InvalidModelStateResponseFactory中得到了正确的结果,我倾向于认为这可能是一个错误。

Startup.cs:

services
    .AddControllers(options =>
    {
        options.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter());
    })
    .ConfigureApiBehaviorOptions(options =>
    {
        options.InvalidModelStateResponseFactory = actionContext =>
        {
            KeyValuePair<string, ModelStateEntry> firstModelErrorPropertyName = actionContext.ModelState.First(s => s.Value.Errors.Count > 0);
            ModelError firstError = firstModelErrorPropertyName.Value.Errors.First();
            ObjectResult toReturn = new ObjectResult(new ErrorResponse
            {
                Status = RequestStatus.Fail,
                ErrorCode = ErrorCode.MissingParameter,
                ErrorDescription = $"Missing POST parameter: {firstModelErrorPropertyName.Key}: {"Description here"}"
            });
            toReturn.StatusCode = 200;
            return toReturn;
        };
    })
    .AddXmlSerializerFormatters()
    .AddXmlDataContractSerializerFormatters()
    .AddXmlOptions(options =>
    {
    })
    .AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.Converters.Add(new JsonStringEnumMemberConverter());
    });

控制器:

/// <summary>
/// Enroll a member in IDCS services.
/// </summary>
/// <returns></returns>
[HttpPost("enroll")]
[Consumes("application/x-www-form-urlencoded")]
[FormatFilter]
public async Task<IActionResult> EnrollAsync(
     [FromForm] EnrollRequest req)
{
    return Ok(new
    {
        content = "Enroll"
    });
}

我在发布后就发现了这个问题。如果我返回一个定义的对象:

return Ok(new EnrollmentSuccessResponse
    {
        Content = "Enroll"
    });

而不是匿名对象

return Ok(new
    {
        content = "Enroll"
    });

一切如预期。

最新更新