繁体   English   中英

ASP.NET Web Api:在ActionFilter / ModelState的错误响应中返回用户友好名称

[英]ASP.NET Web Api: Return user friendly names in error response from ActionFilter/ModelState

我正在使用具有ApiController的视图模型,该模型具有每个属性的Display(Name =“ Friendly Name”)属性。 我创建了一个自定义ActionFilterAttribute以验证模型状态并在模型无效时返回错误请求。 我现在想做的是返回自定义JSON输出,其中包括与每个模型的属性相关的用户友好名称。 我可以想到一些骇人听闻的方法来做到这一点,但是首选的方法是什么?

编辑:这只会在WebApi 5.1中修复。

在这里看看-Web Api ModelState验证忽略了DisplayAttribute


看看Microsoft的官方文档-ApiController.Validate

您可以通过在响应中返回ModelState来实现。 例如

public class MyController : ApiController
    {
        public HttpResponseMessage Post(Product product)
        {
            if (ModelState.IsValid)
            {
                return new HttpResponseMessage(HttpStatusCode.OK);
            }
            else
            {
                return request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
        }
    }

或者,如果您想通过ActionFilterAttribute执行此操作,则可以使用:

public class ValidateModelAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (actionContext.ModelState.IsValid == false)
            {
                actionContext.Response = actionContext.Request.CreateErrorResponse(
                    HttpStatusCode.BadRequest, actionContext.ModelState);
            }
        }
    }

这将返回JSON,例如:

{“ Message”:“请求无效。”,“ ModelState”:{“ product”:[“在JSON中找不到必需的属性'Name'。路径,第1行,位置17。” ],“ product.Name”:[“名称字段为必填。” ],“ product.Weight”:[“该字段的重量必须在0到999之间。” ]}}

在“ ActionFilterAttribute”中,您可以根据自己的API要求自定义错误消息

public class ValidateModelAttribute : ActionFilterAttribute{
public override void OnActionExecuting(HttpActionContext actionContext)
{
    if (actionContext.ModelState.IsValid == false)
    {
        var error = new
        {
            status = false,
            message = "The request is invalid.",
            error = actionContext.ModelState.Values.SelectMany(e => e.Errors.Select(er => er.ErrorMessage))
        };
        actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, error);
    }
}}

{“ status”:否,“ message”:“请求无效。”,“ error”:[“ First Name字段为必填。”,“ Lname字段为必填。”,“ Ename字段为必填。 “ ],}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM