拦截JsonResult并将其包装(作为字符串) [英] Intercept JsonResult and wrap it (as string)
本文介绍了拦截JsonResult并将其包装(作为字符串)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个返回JsonResult的动作.
我想拦截JsonResult返回并用字符串包装.
I have a action that return JsonResult.
I want to intercept the JsonResult return and wrap it with string.
类似的东西:
public class JsonProxyAttribute : FilterAttribute
{
void OnActionExecuting(ExceptionContext filterContext)
{
var res = filterContext.Result as string;
if (res != null)
{
filterContext.Result = "func("+filterContext.Result+")";
}
}
}
所以ajax调用会得到这个:
So the ajax call will get this:
func({"MyContent":"content"})
代替此:
{"MyContent":"content"}
推荐答案
您需要创建一个新的ActionResult
,它将扩展JsonResult
并表示JSONP
What you need is to create a new ActionResult
that will extend JsonResult
and represent 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将如下所示.
Now if you want to intercept regular JSON results, your ActionFilter would look like this.
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
Or you can use JSONP directly in your controllers
public ActionResult Jsonp()
{
var model = new List<string> { "one", "two" };
return new JsonpResult
{
Data = model,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
这篇关于拦截JsonResult并将其包装(作为字符串)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文