打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
webapi支持跨域访问

写在前面

在实际应用中,跨域请求还是比较常见的,如何上接口直接支持跨域的访问呢?

demo

场景项目A有个接口用来获取用户列表,现在项目b也有个功能需要加载用户列表。这两个项目在两个域名下,至少端口好不同。使用angularjs中的$http发起请求。

using Newtonsoft.Json;using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Net.Http;using System.Threading.Tasks;using System.Web.Http;namespace API.Controllers{    public class User    {        public int Id { set; get; }        public string Name { set; get; }        public DateTime Dt { set; get; }    }    public class UserController : ApiController    {        // GET: api/User        [HttpGet]        [Route("api/User/lists")]        public HttpResponseMessage Get()        {                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.NoContent);                List<User> users = new List<User> { new User { Id = 1, Name = "张三", Dt = DateTime.Now },
new User { Id = 2, Name = "李四", Dt = DateTime.Now } }; response = new HttpResponseMessage(HttpStatusCode.OK) {
Content = new StringContent(JsonConvert.SerializeObject(new { _code = 200, _data = users })) }; return response; } }}

首先用postman模拟请求,验证接口是正确的。

现在项目b想通过js来请求这个接口:

$http.get("http://localhost:49505/api/User/lists").success(function (response) { console.log(response); });

结果:

在webapi中为响应头加上允许跨域访问。如下所示

    public class UserController : ApiController    {        // GET: api/User        [HttpGet]        [Route("api/User/lists")]        public HttpResponseMessage Get()        {                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.NoContent);                List<User> users = new List<User> { new User { Id = 1, Name = "张三", Dt = DateTime.Now }, new User { Id = 2, Name = "李四", Dt = DateTime.Now } };                response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(JsonConvert.SerializeObject(new { _code = 200, _data = users })) };                response.Headers.Add("Access-Control-Allow-Origin", "*"); //允许哪些url可以跨域请求到本域                response.Headers.Add("Access-Control-Allow-Methods", "POST"); //允许的请求方法,一般是GET,POST,PUT,DELETE,OPTIONS                response.Headers.Add("Access-Control-Allow-Headers", "x-requested-with,content-type"); //允许哪些请求头可以跨域                return response;        }    }

测试

    $http({        method: 'get',        url: "http://localhost:49505/api/User/lists"    }).success(function (response) { console.log(response); });

结果

 

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
WebAPI的一种单元测试方案
Asp.Net Web API 2第十五课——Model Validation(模型验证)
mvc、webapi杂记
WebApi 路由机制剖析:你准备好了吗?(下)
WebAPi的可视化输出模式(RabbitMQ、消息补偿相关)
HttpResponseMessage && IHttpActionResult
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服