[英]ASP.NET Core and ActionFilter
I move old MVC 5 application to Core, old application has code: 我将旧的MVC 5应用程序移动到Core,旧的应用程序有代码:
public class ValidateApiModelStateAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
Dictionary<string, string> result = new Dictionary<string, string>();
foreach (var key in actionContext.ModelState.Keys)
{
result.Add(key, String.Join(", ", actionContext.ModelState[key].Errors.Select(p => p.ErrorMessage)));
}
// 422 Unprocessable Entity Explained
actionContext.Response = actionContext.Request.CreateResponse<Dictionary<string, string>>((HttpStatusCode)422, result);
}
}
}
so, it means, that if model state is not valid, then we return dictionary with errors and 422 status code (client's requirements). 所以,这意味着,如果模型状态无效,那么我们返回带有错误的字典和422状态代码(客户端的要求)。
I try to rewrite it the following way: 我尝试通过以下方式重写它:
[ProducesResponseType(422)]
public class ValidateApiModelStateAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
Dictionary<string, string> result = new Dictionary<string, string>();
foreach (var key in context.ModelState.Keys)
{
result.Add(key, String.Join(", ", context.ModelState[key].Errors.Select(p => p.ErrorMessage)));
}
// 422 Unprocessable Entity Explained
context.Result = new ActionResult<Dictionary<string, string>>(result);
}
}
}
but it can't be compiled: 但它无法编译:
Cannot implicitly convert type
Microsoft.AspNetCore.Mvc.ActionResult<System.Collections.Generic.Dictionary<string, string>>
toMicrosoft.AspNetCore.Mvc.IActionResult
无法将类型
Microsoft.AspNetCore.Mvc.ActionResult<System.Collections.Generic.Dictionary<string, string>>
隐式转换为Microsoft.AspNetCore.Mvc.IActionResult
how to do it? 怎么做?
Contrary to belief ActionResult<TValue>
is not derived from IActionResult
. 与信念相反
ActionResult<TValue>
不是来自IActionResult
。 Thus the error. 因此错误。
Return new ObjectResult
and set status code as desired. 返回新的
ObjectResult
并根据需要设置状态代码。
[ProducesResponseType(422)]
public class ValidateApiModelStateAttribute : ActionFilterAttribute {
public override void OnActionExecuting(ActionExecutingContext context) {
if (!context.ModelState.IsValid) {
var result = new Dictionary<string, string>();
foreach (var key in context.ModelState.Keys) {
result.Add(key, String.Join(", ", context.ModelState[key].Errors.Select(p => p.ErrorMessage)));
}
// 422 Unprocessable Entity Explained
context.Result = new ObjectResult(result) { StatusCode = 422 };
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.