Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.net Web API - return data from actionfilter

Tags:

I want to return a json object from the wep api actionfilter. 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.

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.

  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);
        }     


    }
}
like image 295
Kumaresan Lc Avatar asked Jun 26 '13 10:06

Kumaresan Lc


2 Answers

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.

like image 188
Darin Dimitrov Avatar answered Oct 02 '22 21:10

Darin Dimitrov


you can use HttpResponseMessage to create the response like that

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
            };
like image 35
tchno0l0ogy Avatar answered Oct 02 '22 21:10

tchno0l0ogy