拦截JsonResult并将其包装(作为字符串)

时间:2013-11-10 14:38:14

标签: asp.net-mvc action-filter

我有一个返回JsonResult的动作 我想拦截JsonResult返回并用字符串包装它。

类似的东西:

 public class JsonProxyAttribute : FilterAttribute
    {
        void OnActionExecuting(ExceptionContext filterContext)
        {
            var res = filterContext.Result as string;
            if (res != null)
            {
                filterContext.Result = "func("+filterContext.Result+")";
            }
        }
    }

所以ajax调用会得到这个:

func({"MyContent":"content"})

而不是:

{"MyContent":"content"}

1 个答案:

答案 0 :(得分:2)

您需要的是创建一个新的ActionResult,它将展开JsonResult并代表JSONP

public class JsonpResult : JsonResult
{
    public override void ExecuteResult(ControllerContext context)
    {
        HttpResponseBase response = context.HttpContext.Response;
        response.ContentType = ContentType ?? "application/x-javascript";
        response.ContentEncoding = ContentEncoding ?? System.Text.Encoding.UTF8;

        if (Data != null)
        {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            string ser = serializer.Serialize(Data);
            response.Write("func(" + ser + ");");
        }
    }
}

现在,如果您想拦截常规JSON结果,您的ActionFilter将如下所示。

public class JsonProxyAttribute : FilterAttribute
{
    void OnActionExecuting(ExceptionContext filterContext)
    {
        var res = filterContext.Result as JsonResult;
        if (res != null)
        {
            filterContext.Result = new JsonpResult
            {
                ContentEncoding = res.ContentEncoding,
                ContentType = res.ContentType,
                Data = res.Data,
                JsonRequestBehavior = res.JsonRequestBehavior
            };
        }
    }
}

或者您可以直接在控制器中使用JSONP

public ActionResult Jsonp()
{
    var model = new List<string> { "one", "two" };
    return new JsonpResult
    {
        Data = model,
        JsonRequestBehavior = JsonRequestBehavior.AllowGet
    };
}