.Net筛选器,用于包装JsonResult操作响应 [英] .Net Filter For Wrapping JsonResult Actions Response

查看:85
本文介绍了.Net筛选器,用于包装JsonResult操作响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经构建了一个 Web API应用程序,并发现了一个问题(当前在我的代码中处理不佳),该问题归纳为包装所有Json对象,这些对象从所有API动作返回的都带有自定义节点(根).

I've built a Web API application and found an issue (which currently treated badly in my code), the issue summarized in wrapping all Json objects which returned from All API actions with custom nodes(roots).

即:我有这个json(数组)响应:

i.e: I have this json (array) response:

[
  {
    "Category": "Pages",
    "Users": [
      {
        "ID": "1",
        "Fname": "Foo",
        "Lname": "Bar"
      }
    ]
  }
]

并且需要此回复:

{
  "Object": {
    "Body": [
      {
        "Category": "Pages",
        "Users": [
          {
            "ID": "1",
            "Fname": "Foo",
            "Lname": "Bar"
          }
        ]
      }
    ]
  }
}

所以这里我只是将响应包装在{"Object":{"Body": <Response Here>}}

So here I just wrapped the response inside {"Object":{"Body": <Response Here>}}

我需要将它应用于类型为Array的所有API Json响应.

And this I need it to be applied on all API Json responses of type Array.

对于简单的Json对象响应,我需要像{"Object": <Response Here>}

And for simple Json object response, I need it just to be wrapped like {"Object": <Response Here>}

我通过以下代码包装了当前每个控制器动作中的Json响应:

I wrapped the Json response currently in each controller action by this code:

 public JsonResult Categories()
 {
   return Json(new { Object= new { Body= GetCategoriesList() } }, JsonRequestBehavior.AllowGet);
 }

确保此成就是如此糟糕,因为我必须在每个动作中都重复进行此包裹.

Sure this achievement is so bad because I have to repeat this wrapping in each action.

我的问题是:

如何创建每个动作执行后要调用的ActionFilterAttribute,以按照上述Json示例包装响应?

How to create ActionFilterAttribute to be called after each action execution to wrap the response as per the above Json sample?

即用于创建过滤器:

 public class JsonWrapper: System.Web.Mvc.ActionFilterAttribute
 {
   public override void OnActionExecuted(ActionExecutedContext filterContext)
   {
   }
 }

即用于调用过滤器:

[JsonWrapper]
public class APIController : Controller

并在同一过滤器中设置响应内容类型"application/json"

And also to set the response content type in the same filter "application/json"

推荐答案

如果在这里假设您要查找的内容:

If suppose here if what you looking for:

public class JsonWrapperAttribute : ActionFilterAttribute, IActionFilter
{
    void IActionFilter.OnActionExecuted(ActionExecutedContext context)
    {
        //Check it's JsonResult that we're dealing with
        JsonResult jsonRes = context.Result as JsonResult;
        if (jsonRes == null)
            return;

        jsonRes.Data = new { Object = new { Body = jsonRes.Data } }
    }
}

这里是使用方式:

[JsonWrapper]
public JsonResult Index()
{
    var data = new
    {
        a = 1,
        b = 2
    };
    return Json(data, JsonRequestBehavior.AllowGet);
}

结果将是:

{"Object":{"Body":{"a":1,"b":2}}}

这篇关于.Net筛选器,用于包装JsonResult操作响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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