之前的一篇博文:jsonp跨域+ashx(示例)
1. 安装 Jsonp 程序集:
PM> Install-Package WebApiContrib.Formatting.Jsonp
PM> Install-Package Microsoft.AspNet.WebApi.Client
PM> Install-Package System.Net.Http.Formatting -Version 4.0.20710(如果安装 Microsoft.AspNet.WebApi.Client 不成功,则安装此程序集)
2. Application_Start 配置:
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
//增加的配置
var config = GlobalConfiguration.Configuration;
GlobalConfiguration.Configuration.AddJsonpFormatter(config.Formatters.JsonFormatter, "callback");
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}
3. Controller 代码:
public class TestController : ApiController
{
[HttpGet]
public string GetBlogUrl()
{
return "cnblogs.com/xishuai/";
}
}
4. JS 调用代码:
function loadBlogUrl() {
$.ajax({
url: 'http://www.cnblogs.com/api/test/GetBlogUrl',
type: 'get',
cache: false,
dataType: 'jsonp',
success: function (data) {
alert(data);
}
});
}