ASP.NET Core和ActionFilter

时间:2018-12-01 18:40:35

标签: c# asp.net-core actionfilterattribute

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

因此,这意味着,如果模型状态无效,那么我们将返回带有错误和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);
        }
    }
}

但无法编译:

  

无法隐式转换类型   Microsoft.AspNetCore.Mvc.ActionResult<System.Collections.Generic.Dictionary<string, string>>Microsoft.AspNetCore.Mvc.IActionResult

怎么做?

1 个答案:

答案 0 :(得分:6)

与信念相反,ActionResult<TValue>不是源自IActionResult。因此就是错误。

返回新的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 };
        }
    }
}