Asp.net Web API - return data from actionfilter

后端 未结 3 1152
猫巷女王i
猫巷女王i 2021-02-04 02:25

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 actionf

3条回答
  •  走了就别回头了
    2021-02-04 03:09

    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.

提交回复
热议问题