Ole*_* Sh 4 c# actionfilterattribute asp.net-core
我将旧的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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
所以,这意味着,如果模型状态无效,那么我们返回带有错误的字典和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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
但它无法编译:
无法隐式转换
Microsoft.AspNetCore.Mvc.ActionResult<System.Collections.Generic.Dictionary<string, string>>为Microsoft.AspNetCore.Mvc.IActionResult
怎么做?
与信仰相反的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 };
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1054 次 |
| 最近记录: |