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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值