【发布时间】:2018-12-01 18:40:35
【问题描述】:
我将旧的 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
怎么做?
【问题讨论】:
-
如果您可以使用 ASP.NET Core 2.1,这是由框架自动完成的
-
@CamiloTerevinto 我的猜测是他们不想要默认的 400 响应,而是想要自定义 422 状态响应。
-
@CamiloTerevinto 自动执行什么操作?我需要准确地返回这个状态码和数据
-
返回新对象结果并设置状态码。
-
@Nkosi 我需要 422 状态码
标签: c# asp.net-core actionfilterattribute