自定义特性
要在WebApi中实现JSONP,一种方式是实现自定义特性 http://*.com/questions/9421312/jsonp-with-asp-net-web-api/
public class JsonCallbackAttribute : ActionFilterAttribute
{
private const string CallbackQueryParameter = "callback"; public override void OnActionExecuted(HttpActionExecutedContext context)
{
var callback = string.Empty; if (IsJsonp(out callback))
{
var jsonBuilder = new StringBuilder(callback);
jsonBuilder.AppendFormat("({0})", context.Response.Content.ReadAsStringAsync().Result);
context.Response.Content = new StringContent(jsonBuilder.ToString());
}
base.OnActionExecuted(context);
} private bool IsJsonp(out string callback)
{
callback = HttpContext.Current.Request.QueryString[CallbackQueryParameter];
return !string.IsNullOrEmpty(callback);
}
}
后面只需要在需要支持JSONP的方法上加上JsonCallback特性即可。
自定义JsonMediaTypeFormatter
大A的文章:http://www.cnblogs.com/artech/p/cors-4-asp-net-web-api-03.html
WebApiContrib.Formatting.Jsonp
https://github.com/WebApiContrib/WebApiContrib.Formatting.Jsonp
Install-Package
WebApiContrib.Formatting.Jsonp
修改Global.asax.cs文件
protected void Application_Start()
{
//add jsonp
GlobalConfiguration.Configuration.AddJsonpFormatter(); AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
需要支持jsonP的方法都加上callback参数即可
public IEnumerable<User> NextPage(int id, string callback = "")
官方的方式
http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
Install-Package Microsoft.AspNet.WebApi.Cors
修改WebApiConfig.Register启用JSONP
config.EnableCors();
在Controller上加上Attribute
[EnableCors(origins: http://jsonpapi.xxxx.net, headers: "*", methods: "*")]
检查防火墙启用了 OPTIONS类型的请求 请求,这个问题找了我好久
REFER:
http://*.com/questions/9421312/jsonp-with-asp-net-web-api
http://edi.wang/post/2013/12/27/tips-for-aspnet-webapi-cors