[英]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.