您需要的是创建一个新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
};
}