1

我有一个返回 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"}
4

1 回答 1

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
    };
}
于 2013-11-10T17:53:17.083 回答