Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify HttpContent (actionExecutedContext.Response.Content) in OnActionExecuted method of WebApi's ActionFilterAttribute

My WebApi action method returns an IQueryable and I want to modify it (apply paging & filtering) through an ActionFilterAttribute in Asp.Net WebApi(Not MVC). The following thread I got how to access the passed model :

.Net Web API IActionFilter.OnActionExecuted return type

but how can I change/replace the whole model with something else?

like image 265
Mahmoud Moravej Avatar asked May 22 '13 09:05

Mahmoud Moravej


1 Answers

I found it!

First I should cast actionExecutedContext.ActionContext.Response.Content into ObjectContent (you should have a refrence to System.Net.Http.Formatting.dll file in your project)

after then you can simply do the following :

public override void OnActionExecuted(System.Web.Http.Filters.HttpActionExecutedContext actionExecutedContext)
{
    IEnumerable model = null;
    actionExecutedContext.Response.TryGetContentValue(out model);
    if (model != null)
    {
        IQueryable modelQuery = model.AsQueryable();

        //Do your modelQuery modification/replacement

        (actionExecutedContext.ActionContext.Response.Content as ObjectContent).Value = modelQuery;
    }

    base.OnActionExecuted(actionExecutedContext);
}

Note : to use TryGetContentValue method you need to import using System.Net.Http; namespace although calling this methoud is not important in the above code.

:: UPDATE ::

If you need to change the Content's value type (for example returning a string instead of IQueryable) you can't simply change the value. You should create a new content like this :

var result = "Something new!";
var oldObjectContent = (actionExecutedContext.ActionContext.Response.Content as ObjectContent);
var newContent = new ObjectContent<string>(result, oldObjectContent.Formatter);
actionExecutedContext.ActionContext.Response.Content = newContent;
like image 113
Mahmoud Moravej Avatar answered Nov 02 '22 23:11

Mahmoud Moravej