首先我们需要定义一个JsonpResult. 代码像这样, 直接继承自JsonResult, override了ExecuteResult方法
public class JsonpResult : JsonResult
{
private static readonly string JsonpCallbackName = "callback";
private static readonly string CallbackApplicationType = "application/json";
/// <summary>
/// Enables processing of the result of an action method by a custom type that inherits from the <see cref="T:System.Web.Mvc.ActionResult"/> class.
/// </summary>
/// <param name="context">The context within which the result is executed.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="context"/> parameter is null.</exception>
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if ((JsonRequestBehavior == JsonRequestBehavior.DenyGet) &&
String.Equals(context.HttpContext.Request.HttpMethod, "GET"))
{
throw new InvalidOperationException();
}
var response = context.HttpContext.Response;
if (!String.IsNullOrEmpty(ContentType))
response.ContentType = ContentType;
else
response.ContentType = CallbackApplicationType;
if (ContentEncoding != null)
response.ContentEncoding = this.ContentEncoding;
if (Data != null)
{
String buffer;
var request = context.HttpContext.Request;
var serializer = new JavaScriptSerializer();
if (request[JsonpCallbackName] != null)
buffer = String.Format("{0}({1})", request[JsonpCallbackName], serializer.Serialize(Data));
else
buffer = serializer.Serialize(Data);
response.Write(buffer);
}
}
}
接着简单定义一个扩展方法:
public static class ContollerExtensions
{
/// <summary>
/// Extension methods for the controller to allow jsonp.
/// </summary>
/// <param name="controller">The controller.</param>
/// <param name="data">The data.</param>
/// <returns></returns>
public static JsonpResult Jsonp(this Controller controller, object data)
{
JsonpResult result = new JsonpResult()
{
Data = data,
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
return result;
}
}
在Controller里使用它:
public JsonpResult GetInformation(string key)
{
string resp = "HELLO WORD!"
return this.Jsonp(resp);
}
现在让我们在另一个站点里使用它:
$.ajax({
url: 'http://localhost:50211/Api/GetInformation',
type: "GET",
dataType: "jsonp",
jsonpCallback: "localJsonpCallback"
});
function localJsonpCallback(json) {
alert(json);
}