Asp.net Web API - returns data from ActionFilter

I want to return a json object from the app-app action filter. How can I achieve this?

I can return an object from an action, but I need to return some data from the actionfilter under some condition.

Thanks in advance.




Edit: 1 When I changed the code as shown below, the browser still loads without response and ends in a timeout error.

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); } } } 
+13
c # asp.net-web-api action-filter
Jun 26 '13 at 10:25
source share
2 answers

All you need to do is assign an answer:

 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 reduce the execution time of the action and immediately return the response we provided.

+33
Jun 26 '13 at 10:40
source share
β€” -

Just add this in case anyone else comes along like me and cannot find the answer to their problem:

Perhaps you are using the wrong import - you have 2 options:

  • System.Web.Http.Filters
  • System.Web.Mvc (or System.Web.Http.Mvc )

Courtesy of Troy Dai from this question: Why is my ASP.NET Web API ActionFilterAttribute OnActionExecuting not starting?

0
Apr 24 '19 at 19:34
source share



All Articles