![](/img/trans.png)
[英]ASP.NET Web Api: Return user friendly names in error response from ActionFilter/ModelState
[英]Asp.net Web API - return data from actionfilter
我想從 wep api actionfilter 返回一個 json 對象。 我怎樣才能做到這一點?
我可以從 action 返回對象,但我需要在某些條件下從 actionfilter 返回一些數據。
提前致謝。
編輯: 1 當我更改如下代碼時,瀏覽器仍在加載但沒有任何響應並以超時錯誤結束。
public class ValidationActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
var modelState = actionContext.ModelState;
if (!modelState.IsValid)
{
List<string> arr = new List<string>();
foreach (var key in modelState.Keys)
{
var state = modelState[key];
if (state.Errors.Any())
{
string er = state.Errors.First().ErrorMessage;
if (!string.IsNullOrEmpty(er))
{
arr.Add(er);
}
}
}
var output = new Result() { Status = Status.Error.ToString(), Data = null, Message = arr };
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.BadRequest, output, actionContext.ControllerContext.Configuration.Formatters.JsonFormatter);
}
}
}
您只需要分配響應:
public class MyActionFilterAttribute: ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
actionContext.Response = actionContext.Request.CreateResponse(
HttpStatusCode.OK,
new { foo = "bar" },
actionContext.ControllerContext.Configuration.Formatters.JsonFormatter
);
}
}
假設以下控制器操作:
[MyActionFilter]
public string Get()
{
return "OK";
}
這個自定義動作過濾器將短路動作的執行並直接返回我們提供的響應。
您可以使用 HttpResponseMessage 來創建這樣的響應
var output = new Result() { Status = Status.Error.ToString(), Data = null, Message = arr };
actionContext.Response = new HttpResponseMessage {
Content = new StringContent(JsonConvert.SerializeObject(output), Encoding.UTF8, "application/json"),
StatusCode = HttpStatusCode.OK
};
只是把它扔在那里,以防其他人像我一樣來到這里並且沒有找到他們問題的答案:
您可能使用了錯誤的導入 - 您有兩個選擇:
System.Web.Http.Filters
System.Web.Mvc
(或System.Web.Http.Mvc
)來自這個問題的 Troy Dai 的禮貌: Why is my ASP.NET Web API ActionFilterAttribute OnActionExecuting not fire?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.