MVC.Net:WebAPI添加对jsonP的支持

在某些情况下,我们需要在WebAPI项目中添加对jsonP的支持。比如我们同时创建了MVC.Net和WebAPI两个项目,这两个项目使用不同的端口,这时如果MVC.Net项目的前端想要直接访问WebAPI项目,就会出现“cross-origin”的错误。要解决这个问题,我们通常会使用jsonP的方法。

要让WebAPI支持返回jsonP格式,需要的步骤如下:

1. 通过NuGet安装WebApiContrib.Formatting.Jsonp。项目地址:https://github.com/WebApiContrib/WebApiContrib.Formatting.Jsonp

2. 然后在修改Global.asax.cs文件,代码如下:

 1 public class WebApiApplication : System.Web.HttpApplication
 2 {
 3     protected void Application_Start()
 4     {
 5         AreaRegistration.RegisterAllAreas();
 6 
 7         // 添加对jsonP格式的支持
 8         GlobalConfiguration.Configuration.AddJsonpFormatter();
 9 
10         GlobalConfiguration.Configure(WebApiConfig.Register);
11         FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
12         RouteConfig.RegisterRoutes(RouteTable.Routes);
13         BundleConfig.RegisterBundles(BundleTable.Bundles);
14     }
15 }

3. 最后就是记得修改Action,将需要支持jsonP的方法都加上callback参数,例如

public IEnumerable<PostViewModel> NextPage(int id, string callback = "")

这样WebAPI就支持jsonP格式的调用了。

原文地址:https://www.cnblogs.com/ilovewindy/p/3759912.html