写在前面

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

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); });

结果

webapi支持跨域访问的更多相关文章

  1. .Net WebApi 支持跨域访问使用 Microsoft.AspNet.WebApi.Cors

    首先导入Cors库,通过程序包管理控制台导入 Install-Package Microsoft.AspNet.WebApi.Cors 引用库之后,我们需要进行简单的配置. 现在WebApiConfi ...

  2. Asp.Net Web Api 接口,拥抱支持跨域访问。

    如何让你的 Asp.Net Web Api 接口,拥抱支持跨域访问. 由于 web api 项目通常是被做成了一个独立站点,来提供数据,在做web api 项目的时候,不免前端会遇到跨域访问接口的问题 ...

  3. SpringMvc支持跨域访问,Spring跨域访问,SpringMvc @CrossOrigin 跨域

    SpringMvc支持跨域访问,Spring跨域访问,SpringMvc @CrossOrigin 跨域 >>>>>>>>>>>> ...

  4. SpringMvc支持跨域访问,Spring跨域访问,SpringMvc @CrossOrigin 跨域[转]

    SpringMvc支持跨域访问,Spring跨域访问,SpringMvc @CrossOrigin 跨域 原文地址:https://www.cnblogs.com/fanshuyao/p/716847 ...

  5. nginx:支持跨域访问

    在http节点中配置: #支持跨域访问 add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Header ...

  6. 如何让你的 Asp.Net Web Api 接口,拥抱支持跨域访问。

    由于 web api 项目通常是被做成了一个独立站点,来提供数据,在做web api 项目的时候,不免前端会遇到跨域访问接口的问题. 刚开始没做任何处理,用jsonp的方式调用 web api 接口, ...

  7. WebAPI的跨域访问CORS三种方法

    跨域访问: JSONP的原理利用<script>没有跨域访问的限制,利用<script>的src跨域访问api,api会根据数据把json包装在一个js里面,这样跨域的客户端拿 ...

  8. 使用Cors后台设置WebAPI接口跨域访问

    昨天根据项目组前端开发工程师反映,在浏览器端无法直接使用ajax访问后台接口获取数据,根据他的反映,我查阅了相关跨域的解决方案: 一:使用jsonP,但是jsonP只能使用GET请求,完全不符合我项目 ...

  9. 使chrome支持跨域访问

    在做后台开发的时候,使用了iframe框架.后台主页面如下: <div style="width:185px; overflow: hidden;" id="wes ...

随机推荐

  1. 【BZOJ-4310】跳蚤 后缀数组 + ST表 + 二分

    4310: 跳蚤 Time Limit: 20 Sec  Memory Limit: 512 MBSubmit: 180  Solved: 83[Submit][Status][Discuss] De ...

  2. Input path does not exist: file:/.......

    注意看是file不存在并不是hdfs,好奇怪,突然明白应该是路径不对,必须加上hdfs://hostname:port/file. 我为什么饭这样的错误是因为前一阵谢了HDFS的曹组,谢了全局File ...

  3. POJ 3662 Telephone Lines(二分+最短路)

    查看题目 最小化第K大值. 让我怀疑人生的一题目,我有这么笨? #include <cstdio> #include <queue> #include <cstring& ...

  4. 数据结构算法C语言实现(十四)--- 4.1&4.2串的类型定义、表示及实现

    一.简述 [暂无] 二.头文件 //4_2_part1.h /** author:zhaoyu */ //2016-6-10 //----串的定长顺序存储表示---- #include "h ...

  5. <转>iOS9 Day-by-Day:iOS开发者必须了解的iOS 9新技术与API

    iOS9 Day-by-Day是作者Chris Grant新开的一个系列博客,覆盖了iOS开发者必须知道的关于iOS 9的新技术与API,并且还进行了实际操作演练,每篇文章中相关的代码Chris都会将 ...

  6. [MacOS NSAlert的使用]

    源:http://helloitworks.com/863.html NSAlert用于弹出一个确认对话框,在程序中被广泛地使用.常见的场景是用户删除数据,会弹出对话框给用户确认,免得用户不小心导致了 ...

  7. GoJS使用

    1. 先学习官网的这篇Get Started with GoJS教程入门,了解GoJS基础知识: 2. 浏览GoJS各个示例(Samples.Intro),找到契合自己业务需要的某个或者某几个例子,然 ...

  8. 屠蛟之路_蛟灵岛战役(下)_SeventhDay

    蛟灵山,蛟灵洞,beta蛟. 终极决斗的时刻,这又是一场不是你死就是我亡的战争! beta怪蛟法力虽然没有alpha恶龙强,但是它依仗着地利,对屠蛟少年们发起了一次次极具威胁性地攻击!少年们的身上添了 ...

  9. 9 HTML&JS等前端知识系列之Ajax post请求带有token向Django请求

    我们 在母板上写入这段代码: <script type="text/javascript"> // 个人定义大函数,不是重点,可以忽略 $(document).read ...

  10. Winsock 入门 判读主机字节序 示例

    #include <stdio.h> union endian_u { /*最大成员的长度就是联合成员的长度.联合可以在定义时直接进行初始化,但这个初始化必须是联合第一个成员的类型,所以把 ...