Modify HttpContent (actionExecutedContext.Response

2020-03-03 06:20发布

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?

1条回答
放我归山
2楼-- · 2020-03-03 07:11

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;
查看更多
登录 后发表回答