Asp.net Web API - return data from actionfilter
Asked Answered
M

3

21

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


    }
}
Mendie answered 26/6, 2013 at 10:25 Comment(0)
H
45

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.

Hoick answered 26/6, 2013 at 10:40 Comment(4)
How do I do this in .net core?Substitutive
For me the above solution didn't work. The code in the action was still executed.Chipboard
@GilesRoberts I've tried to call actionContext.ModelState.AddModelError() to make model invalid. Then I'm checking for if (!context.ModelState.IsValid) and if it is not valid error is returned. Json error is shown in the browser window (or by curl.exe tool)Antefix
can any one tell me how the controller consume action filter response? For the above example, I want to use the "bar" value in my controller. How to achieve this?Humbuggery
M
1

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)

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

Myles answered 24/4, 2019 at 19:34 Comment(0)
C
1

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
            };
Cellule answered 11/2, 2020 at 12:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.