修改HttpContent(actionExecutedContext.Response.Content)中的WebAPI的ActionFilterAttribute的OnActionExecuted方法 [英] Modify HttpContent (actionExecutedContext.Response.Content) in OnActionExecuted method of WebApi's ActionFilterAttribute

查看:4841
本文介绍了修改HttpContent(actionExecutedContext.Response.Content)中的WebAPI的ActionFilterAttribute的OnActionExecuted方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的WebAPI操作方法返回一个IQueryable,我想修改(适用分页和放大器;过滤)通过ActionFilterAttribute在Asp.Net的WebAPI(不MVC)。
以下螺纹我如何访问所传递的模型:

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 :

<一个href=\"http://stackoverflow.com/questions/16137189/net-web-api-iactionfilter-onactionexecuted-return-type\">.Net网页API IActionFilter.OnActionExecuted返回类型

但有别的东西,我怎么能更改/替换整个模型?

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

推荐答案

我找到了!

首先,我要投 actionExecutedContext.ActionContext.Response.Content ObjectContent (你应该有一个refrence到< code在您的项目

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

注意:使用 TryGetContentValue 方法,你需要导入使用System.Net.Http; 命名空间虽然调用此methoud是不是在上面的code很重要的。

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.

::更新::

如果您需要更改内容的值类型(例如返回一个字符串,而不是IQueryable的),你不能简单地改变该值。您应该创建这样一个新的内容:

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;

这篇关于修改HttpContent(actionExecutedContext.Response.Content)中的WebAPI的ActionFilterAttribute的OnActionExecuted方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆