支持Ajax跨域访问ASP.NET Web Api 2(Cors)的简单示例教程演示
随着深入使用ASP.NET Web Api,我们可能会在项目中考虑将前端的业务分得更细。比如前端项目使用Angularjs的框架来做UI,而数据则由另一个Web Api 的网站项目来支撑。注意,这里是两个Web网站项目了,前端项目主要负责界面的呈现和一些前端的相应业务逻辑处理,而Web Api则负责提供数据。
这样问题就来了,如果前端通过ajax访问Web Api项目话,就涉及到跨域了。我们知道,如果直接访问,正常情况下Web Api是不允许这样做的,这涉及到安全问题。所以,今天我们这篇文章的主题就是讨论演示如何配置Web Api以让其支持跨域访问(Cors)。好了,下面我们以一个简单的示例直接进入本文的主题。
首先打开Visual Studio 2013,创建一个空白的解决方案,命名为:Solution.Cors。
再创建一个空的Web Api 项目,命名为:CorsDemo.Api,如下图:
接着我们右键单击刚才创建的解决方案,如下:
创建一个空的Web网站,命名为:CorsDemo.UI,如下:
好了,完成以上步骤,你将看到如下的解决方案目录:
下面我们在CorsDemo.UI的网站项目中通过Nuget程序包管理工具来添加我们需要的jQuery和Bootstrap包(引入 Bootstrap主要是为了美化我们的界面的,只需要一两个css class就能制作出一个精美漂亮的按钮,下文你将看到)。以下是添加jQuery包的界面:
按照上图方法引用Bootstrap。到这里,我们的准备工作就完成了。下面开始创建一个Web Api的示例控制器:UserController,这个控制器中只有一个返回IEnumerable<T>的方法,具体代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | using CorsDemo.Api.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace CorsDemo.Api.Controllers { [RoutePrefix( "api/user" )] public class UserController : ApiController { [HttpGet, Route( "list" )] public IEnumerable<User> GetUserList() { return new List<User> { new User{Id=1,Name= "Admin" ,Locked= false ,CreateOn=DateTime.Now.ToShortDateString()}, new User{Id=2,Name= "Peter" ,Locked= false ,CreateOn=DateTime.Now.ToShortDateString()}, new User{Id=3,Name= "Employee" ,Locked= true ,CreateOn=DateTime.Now.ToShortDateString()} }; } } } |
User类:
1 2 3 4 5 6 7 8 9 10 | namespace CorsDemo.Api.Models { public class User { public int Id { get ; set ; } public string Name { get ; set ; } public string CreateOn { get ; set ; } public bool Locked { get ; set ; } } } |
如果我们现在运行CorsDemo.Api这个项目,并打开:http://localhost:4543/api/user/list这个地址,我们将在浏览器中看到XML格式的输出,如下:
我们修改一下App_Start目录下的WebApiConfig.cs文件,让其默认输出json格式的数据,如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | using System; using System.Collections.Generic; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; namespace CorsDemo.Api { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API 配置和服务 // Web API 路由 config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi" , routeTemplate: "api/{controller}/{id}" , defaults: new { id = RouteParameter.Optional } ); config.Formatters.JsonFormatter.SupportedMediaTypes.Add( new MediaTypeHeaderValue( "text/html" )); } } } |
重新生成CorsDemo.Api项目并打开http://localhost:4543/api/user/list,这时我们可以得到json的数据,如下:
[{“Id”:1,”Name”:”Admin”,”CreateOn”:”2015/10/26″,”Locked”:false},{“Id”:2,”Name”:”Peter”,”CreateOn”:”2015/10/26″,”Locked”:false},{“Id”:3,”Name”:”Employee”,”CreateOn”:”2015/10/26″,”Locked”:true}]
好了,到这里我们Web Api端的数据输出就准备好了。为了测试是否可以跨域访问,我们再转到CorsDemo.UI网站项目中。首先创建一个cors-demo.html页面(这个命名自己可以任意取)后打开,修改成如下的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | <! DOCTYPE html> < html xmlns="http://www.w3.org/1999/xhtml"> < head > < meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> < title >Web Api 2 Cors Demo</ title > < link href="Content/bootstrap.css" rel="stylesheet" /> < script src="Scripts/jquery-1.9.1.js"></ script > < script src="Scripts/bootstrap.js"></ script > </ head > < body > < a class="btn btn-primary" id="getData">跨域获取数据</ a > < script type="text/javascript"> $("#getData").click(function () { $.ajax({ url: "http://localhost:4543/api/user/list", success: function (response) { console.log(response); } }); }); </ script > </ body > </ html > |
完成以下步骤后,我们在Visual Studio中cors-demo.html上右键单击,在弹出的窗口中选择“在浏览器中查看”,Visual Studio会自动在默认的浏览器(我这里的浏览器是Firefox)中打开cors-demo.html这个页面。为了测试,我们先点击一下这个页面中 的“跨域获取数据”这个按钮(为了查看此时Web Api是否支持跨域访问,我们需先打开Firefox的firebug插件,并定位到“控制台”选项卡)。
ajax请求结束后,我们会在控制台看到如下结果:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:4543/api/user/list. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
怎么样,是不是提示我们:跨域请求被阻止,同时提示CORS头部信息缺失,所以我们可以去Web Api配置CORS来让其支持跨域访问。
那现在我们就到CorsDemo.Api这个项目中去配置关于CORS的支持。不需要太多,在WebApiConfig.cs文件中配置HttpConfiguration的EnableCors方法即可。在修改配置前,我们需要通过Nuget来新增一些引用(Microsoft.AspNet.WebApi.Cors,它的依赖包会被自动引用到项目中
),如下:
修改后的WebApiConfig.cs文件如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | using System; using System.Collections.Generic; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Cors; namespace CorsDemo.Api { 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}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html")); } private static void EnableCrossSiteRequests(HttpConfiguration config) { var cors = new EnableCorsAttribute( origins: "*", headers: "*", methods: "*" ); config.EnableCors(cors); } } } |
现在,我们再重新生成CorsDemo.Api项目并运行,接着在页面http://localhost:4631/cors-demo.html中点击按钮“跨域获取数据”,通过firebug的控制台,我们可以看到数据跨域加载成功了,如下:
好了,这篇关于ASP.NET Web Api支持跨域请求的示例和演示就完成了。
几点补充:
1.EnableCorsAttribute构造函数中的参数可以根据自己情况进行设置,比如origins,当其为”*”时,所以的域都可访问api的资源,如果你只想要指定的域可访问资源,则指定到具体的域即可
2.在Web Api的控制器中,我们还对单个Action进行跨域访问限制,只需要在Action上设置EnableCors属性即可,如:
1 2 3 4 5 6 | [HttpGet] [EnableCors("http://example.com","*","*")] public User GetUser() { return new User { Id = 1, Name = "Admin", Locked = false, CreateOn = DateTime.Now.ToShortDateString() }; } |
特别注意:以上只是支持Web Api跨域的示例,其中存在安全验证等问题并没有提及。所以,如需要正式的生产项目使用本文的技术,请在需要的时候考虑有关安全验证等问题。安全问题,安全问题,安全问题。。。重要的事情说三遍!!!
专注.NET开发的爱好者知识社区--【https://codedefault.com】。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· 展开说说关于C#中ORM框架的用法!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?