[英]ASP.Net Core Validation Problem State - Binding validation not returning problem details
同樣的問題發布在這里: https : //github.com/aspnet/Mvc/issues/8564
我有一個問題,當執行命中控制器時,我的代碼顯式返回ValidationProblemDetails響應。
但是,當綁定驗證阻止執行到達控制器時,我得到以下JSON響應(標准模型狀態驗證對象)。
{
"Email": [
"Invalid email address"
]
}
為什么不在響應中返回驗證問題詳細信息?
我正在使用Microsoft.AspNetCore.App
2.1.4包。
請求模型
public class RegistrationRequest
{
[Description("Given Name")]
[MaxLength(100)]
[Required(ErrorMessage = "Given Name is required")]
public string GivenName { get; set; }
[MaxLength(100)]
[Required(ErrorMessage = "Surname is required")]
public string Surname { get; set; }
[MaxLength(255)]
[Required(ErrorMessage = "Email is required")]
[EmailAddress(ErrorMessage = "Invalid email address")]
public string Email { get; set; }
[Required(ErrorMessage = "Password is required")]
public string Password { get; set; }
[Description("Confirm Password")]
[Compare(nameof(Password), ErrorMessage = "Passwords do not match")]
public string ConfirmPassword { get; set; }
}
啟動
public class Startup
{
public IServiceProvider ConfigureServices(IServiceCollection services)
{
...
services.Configure<ApiBehaviorOptions>(options =>
{
options.InvalidModelStateResponseFactory = context =>
{
var problemDetails = new ValidationProblemDetails(context.ModelState)
{
Instance = context.HttpContext.Request.Path,
Status = (int)HttpStatusCode.BadRequest,
Detail = "Please refer to the errors property for additional details"
};
return new BadRequestObjectResult(problemDetails)
{
ContentTypes = "applicaton/json"
};
};
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
...
}
}
調節器
[ApiController]
[Authorize]
[Route("users")]
public sealed class UserController : Controller
{
public UserController(
UserManager userManager,
IMapper mappingProvider)
{
Manager = userManager;
Mapper = mappingProvider;
}
private UserManager Manager { get; }
private IMapper Mapper { get; }
[HttpPost]
[AllowAnonymous]
[Consumes("application/json")]
[Produces("application/json")]
[ProducesResponseType(200)]
[ProducesResponseType(400, Type = typeof(ValidationProblemDetails))]
public async Task<IActionResult> Post([FromBody]ApiModels.RegistrationRequest request)
{
if (request == null) throw new ArgumentNullException(nameof(request));
var user = Mapper.Map<DataModels.User>(request);
var result = await Manager.Create(user, request.Password); // return OperationResult
return result.ToActionResult();
}
}
將OperationResult轉換為IActionResult的擴展方法
public static class OperationResultExtensions
{
public static ValidationProblemDetails ToProblemDetails(this OperationResult result)
{
if (result == null) throw new ArgumentNullException(nameof(result));
var problemDetails = new ValidationProblemDetails()
{
Status = (int)HttpStatusCode.BadRequest
};
if (problemDetails.Errors != null)
{
result.Errors
.ToList()
.ForEach(i => problemDetails.Errors.Add(i.Key, i.Value.ToArray()));
}
return problemDetails;
}
public static IActionResult ToActionResult(this OperationResult result)
{
switch (result.Status)
{
case HttpStatusCode.OK:
return new OkResult();
case HttpStatusCode.NotFound:
return new NotFoundResult();
case HttpStatusCode.BadRequest:
var problems = result.ToProblemDetails();
return new BadRequestObjectResult(problems);
default:
return new StatusCodeResult((int)result.Status);
}
}
}
你必須Configure<ApiBehaviorOptions>
前 AddMvc
:將呼叫AddMvc
注冊一個類實現IConfigureOptions<ApiBehaviorOptions>
這最終覆蓋您已經使用配置實例services.Configure<ApiBehaviorOptions>
和有效復位工廠函數 。
要使其正常工作,您需要做的就是在ConfigureServices
切換順序:
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.Configure<ApiBehaviorOptions>(options =>
{
options.InvalidModelStateResponseFactory = context =>
{
...
};
});
我也注意到雖然它不完全是粗體 ,但是文檔表明這種排序也很重要:
在services.AddMvc()之后的Startup.ConfigureServices中添加以下代碼.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.Configure<ApiBehaviorOptions>(options => ... );
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.