ASP.NET 核心和 ActionFilter

ASP.NET Core and ActionFilter

我将旧的 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);
        }
    }
}

所以,这意味着,如果模型状态无效,那么我们 return 字典有错误和 422 状态代码(客户的要求)。

我尝试按以下方式重写它:

[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);
        }
    }
}

但是无法编译:

Cannot implicitly convert type Microsoft.AspNetCore.Mvc.ActionResult<System.Collections.Generic.Dictionary<string, string>> to Microsoft.AspNetCore.Mvc.IActionResult

怎么做?

与信念相反 ActionResult<TValue> 并非源自 IActionResult。因此错误。

Return new 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 };
        }
    }
}