[英]Asp.net Web API - return data from actionfilter
I want to return a json object from the wep api actionfilter.我想从 wep api actionfilter 返回一个 json 对象。 How can I achieve this?
我怎样才能做到这一点?
I can return the object from action but I need to return some data from the actionfilter on some condition.我可以从 action 返回对象,但我需要在某些条件下从 actionfilter 返回一些数据。
Thanks in advance.提前致谢。
Edit: 1 When I changed the code like the following, the browser still loading without any response and ends in timeout error.编辑: 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);
}
}
}
All you need is to assign the Response:您只需要分配响应:
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
);
}
}
Assuming the following controller action:假设以下控制器操作:
[MyActionFilter]
public string Get()
{
return "OK";
}
this custom action filter will short-circuit the execution of the action and directly return the response we provided.这个自定义动作过滤器将短路动作的执行并直接返回我们提供的响应。
you can use HttpResponseMessage to create the response like that您可以使用 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
};
Just throwing this out there in case anyone else comes here like me and doesn't find an answer to their problem:只是把它扔在那里,以防其他人像我一样来到这里并且没有找到他们问题的答案:
You may be using the wrong import - You have 2 options:您可能使用了错误的导入 - 您有两个选择:
System.Web.Http.Filters
System.Web.Mvc
(or System.Web.Http.Mvc
) System.Web.Mvc
(或System.Web.Http.Mvc
) Courtesy of Troy Dai from this question: Why is my ASP.NET Web API ActionFilterAttribute OnActionExecuting not firing?来自这个问题的 Troy Dai 的礼貌: Why is my ASP.NET Web API ActionFilterAttribute OnActionExecuting not fire?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.