写在前面
在实际应用中,跨域请求还是比较常见的,如何上接口直接支持跨域的访问呢?
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 = , Name = "张三", Dt = DateTime.Now },
new User { Id = , Name = "李四", Dt = DateTime.Now } };
response = new HttpResponseMessage(HttpStatusCode.OK) {
Content = new StringContent(JsonConvert.SerializeObject(new { _code = , _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 = , Name = "张三", Dt = DateTime.Now }, new User { Id = , Name = "李四", Dt = DateTime.Now } };
response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(JsonConvert.SerializeObject(new { _code = , _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); });
结果