c# - ASP.NET Core 和 ActionFilter
问题描述
我将旧的 MVC 5 应用程序移动到核心,旧应用程序有代码:
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
怎么做?
解决方案
出乎意料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 };
}
}
}
推荐阅读
- docker - 我无法在 docker 容器中获取 access_token,失败并出现 502 bad gateway
- ios - 如何使用 ffmpeg 命令在视频中添加节拍和低音效果?
- axios - 是否可以从 JSONplaceholder 获取数组并使用 axios 将其存储在文件中?
- javascript - 从 HTTPS 网页访问的 localhost HTTP。为什么没有“混合内容”错误?
- python - 如何使用 QCheckBox 过滤 QListWidget 中的项目
- python - 比较两个数据帧并将第二个数据帧中的新值添加到第一个数据帧
- java - 如何在 Java 中的 LinearLayout 中设置边距?
- performance - 有没有办法生成 perl 5.30 字节码或可执行文件?
- sql - SQLSERVER - 计算网络图中的节点循环
- reactjs - 反应滚动水平滚动不起作用