当前位置: 移动技术网 > IT编程>开发语言>.net > 支持Ajax跨域访问ASP.NET Web Api 2(Cors)的示例教程

支持Ajax跨域访问ASP.NET Web Api 2(Cors)的示例教程

2017年12月12日  | 移动技术网IT编程  | 我要评论

电商,钢笔行书字帖欣赏,男子假冒老总招模特

随着深入使用asp.net web api,我们可能会在项目中考虑将前端的业务分得更细。比如前端项目使用angularjs的框架来做ui,而数据则由另一个web api 的网站项目来支撑。注意,这里是两个web网站项目了,前端项目主要负责界面的呈现和一些前端的相应业务逻辑处理,而web api则负责提供数据。

这样问题就来了,如果前端通过ajax访问web api项目话,就涉及到跨域了。我们知道,如果直接访问,正常情况下web api是不允许这样做的,这涉及到安全问题。所以,今天我们这篇文章的主题就是讨论演示如何配置web api以让其支持跨域访问(cors)。好了,下面我们以一个简单的示例直接进入本文的主题。

首先打开visual studio 2013,创建一个空白的解决方案,命名为:crossdomainaccesswebapi。

再创建一个空的web api项目,命名为:crossdomainaccess.webapi

接着我们右键单击刚才创建的解决方案,创建一个空的web项目用来模拟我们的网站对webapi项目进行跨域调用,如下:

完成以上步骤以后,我们的解决方案目录如下图所示:

下面我们在模拟网站的web项目中通过nuget添加jquery,一下是添加jquery包的界面:

添加完成后,到这里我们就完成了前期的准备工作。下面在webapi项目的models文件夹中添加是一个实体类userinfo,具体代码如下:

using system;
using system.collections.generic;
using system.linq;
using system.web;

namespace crossdomainaccess.webapi.models
{
 public class userinfo
 {
  public int id { get; set; }

  public string username { get; set; }

  public string userpass { get; set; }

  public string email { get; set; }

  public datetime regtime { get; set; }
 }
}

然后在webapi项目中添加一个示例控制器:userinfocontroller,这个控制器用来返回数据集合,具体代码如下:

using system;
using system.collections.generic;
using system.linq;
using system.net;
using system.net.http;
using system.web.http;
using crossdomainaccess.webapi.models;

namespace crossdomainaccess.webapi.controllers
{
 public class userinfocontroller : apicontroller
 {
  /// <summary>
  /// 获取用户信息集合的方法
  /// </summary>
  /// <returns>返回用户信息集合</returns>
  public ihttpactionresult getlist()
  {
   //对象集合模拟数据
   list<userinfo> list = new list<userinfo>()
   {
    new userinfo()
    {
     id = 1,
     username = "张三",
     userpass = "fdasdfas",
     email = "zhangsan@163.com",
     regtime = datetime.now
    },
    new userinfo()
    {
     id = 2,
     username = "李四",
     userpass = "fdasdfas",
     email = "lisi@163.com",
     regtime = datetime.now
    },
    new userinfo()
    {
     id = 3,
     username = "王五",
     userpass = "fdasdfas",
     email = "wangwu@163.com",
     regtime = datetime.now
    },
    new userinfo()
    {
     id = 4,
     username = "赵六",
     userpass = "fdasdfas",
     email = "zhaoliu@163.com",
     regtime = datetime.now
    },
    new userinfo()
    {
     id = 5,
     username = "田七",
     userpass = "fdasdfas",
     email = "tianqi@163.com",
     regtime = datetime.now
    },
    new userinfo()
    {
     id = 6,
     username = "王八",
     userpass = "fdasdfas",
     email = "wangba@163.com",
     regtime = datetime.now
    }
   };
   return ok(list);
  }
 }
}

接着我们需要修改一下app_start目录下的webapiconfig.cs文件中webapi的路由规则,以便通过api/{controller}/{action}的方式进行访问,同时让修改序列化方式,让webapi默认输出json格式的数据,具体操作如下:

using system;
using system.collections.generic;
using system.linq;
using system.net.http.formatting;
using system.web.http;

namespace crossdomainaccess.webapi
{
 public static class webapiconfig
 {
  public static void register(httpconfiguration config)
  {
   // web api 配置和服务

   // web api 路由
   config.maphttpattributeroutes();

   config.routes.maphttproute(
    name: "defaultapi",
    routetemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = routeparameter.optional }
   );
   //清除所有序列化格式
   config.formatters.clear();
   //添加json格式的序列化器
   config.formatters.add(new jsonmediatypeformatter());
  }
 }
}

重新生成一下项目,并在浏览器中访问,这时我们可以的到json格式的数据,如下:

复制代码 代码如下:
[{"id":1,"username":"张三","userpass":"fdasdfas","email":"zhangsan@163.com","regtime":"2016-04-21t10:36:50.7800569+08:00"},{"id":2,"username":"李四","userpass":"fdasdfas","email":"lisi@163.com","regtime":"2016-04-21t10:36:50.7800569+08:00"},{"id":3,"username":"王五","userpass":"fdasdfas","email":"wangwu@163.com","regtime":"2016-04-21t10:36:50.7800569+08:00"},{"id":4,"username":"赵六","userpass":"fdasdfas","email":"zhaoliu@163.com","regtime":"2016-04-21t10:36:50.7800569+08:00"},{"id":5,"username":"田七","userpass":"fdasdfas","email":"tianqi@163.com","regtime":"2016-04-21t10:36:50.7800569+08:00"},{"id":6,"username":"王八","userpass":"fdasdfas","email":"wangba@163.com","regtime":"2016-04-21t10:36:50.7800569+08:00"}]

好了,到这里我们web api端的数据输出就准备好了。为了测试是否可以跨域访问,我们再转到corsdemo.ui网站项目中。首先创建一个index.aspx页面(这个命名自己可以任意取)后打开,修改成如下的代码:

<%@ page language="c#" autoeventwireup="true" codebehind="index.aspx.cs" inherits="crossdomainaccess.web.index" %>

<!doctype html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <meta http-equiv="content-type" content="text/html; charset=utf-8" />
 <title></title>
 <script src="scripts/jquery-2.2.3.min.js"></script>
 <script type="text/javascript">
  $(function () {
   $('#getdata').click(function () {
    $.ajax({
     url: 'http://localhost:29867/api/userinfo/getlist',
     datatype: 'json',
     success: function (data) {
      //以表格的形式在浏览器控制台显示数据,ie下不支持
      console.table(data);
     }
    });
   });
  });
 </script>
</head>
<body>
 <form id="form1" runat="server">
  <div>
   <input type="button" value="跨域获取数据" id="getdata" />
  </div>
 </form>
</body>
</html>

完成以上步骤以后,启动webapi项目和web项目,并在web项目的index页面中点击跨域获取数据按钮,打开浏览器控制台查看请求结果,在控制台会出现如下结果:

控制台提示我们跨域请求被阻止,同时提示cors头部信息确实,所以我们可以通过去webapi配置cors来让其支持跨域访问。

那现在我们在webapi项目中通过nuget添加microsoft.aspnet.webapi.cors ,然后在webapiconfig.cs文件中配置httpconfiguration的enablecors方法即可。具体操作如下:

using system;
using system.collections.generic;
using system.linq;
using system.net.http.formatting;
using system.web.http;
using system.web.http.cors;

namespace crossdomainaccess.webapi
{
 public static class webapiconfig
 {
  public static void register(httpconfiguration config)
  {
   // web api 配置和服务
   enablecrosssiterequests(config);
   // web api 路由
   config.maphttpattributeroutes();

   config.routes.maphttproute(
    name: "defaultapi",
    routetemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = routeparameter.optional }
   );
   //清除所有序列化格式
   config.formatters.clear();
   //添加json格式的序列化器
   config.formatters.add(new jsonmediatypeformatter());
  }

  /// <summary>
  /// 允许跨域调用
  /// </summary>
  /// <param name="config"></param>
  private static void enablecrosssiterequests(httpconfiguration config)
  {
   //对所有的请求来源没有任何限制
   var cors = new enablecorsattribute(
    origins: "*",
    headers: "*",
    methods: "*"
    );
   config.enablecors(cors);
  }
 }
}

现在,我们再重新生成webapi项目并运行,接着在页面http://localhost:31521/index.aspx中点击按钮“跨域获取数据”,通过firebug的控制台,我们可以看到数据跨域加载成功了,如下:

更多精彩内容,请点击《ajax跨域技术汇总》,进行深入学习和研究。

至此,关于asp.net web api支持跨域请求的示例和演示就完成了,谢谢大家的阅读。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网