写在前面

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

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. random模块

    如下 #!/usr/bin/env python # encoding: utf-8 import sys import platform print (platform.python_version ...

  2. 浏览器上网 (Safari & Chrome)

    浏览器上网 (Safari & Chrome) Command + L = 光标移到地址框 Command + R = 刷新页面 Command + + = 大屏幕的时候很实用,放大页面,基本 ...

  3. 【BZOJ-3790】神奇项链 Manacher + 树状数组(奇葩) + DP

    3790: 神奇项链 Time Limit: 10 Sec  Memory Limit: 64 MBSubmit: 304  Solved: 150[Submit][Status][Discuss] ...

  4. DayuCMS 1.525 /include/global.func.php Foreground Arbitrary Code Execution

    catalog . 漏洞描述 . 漏洞触发条件 . 漏洞影响范围 . 漏洞代码分析 . 防御方法 . 攻防思考 1. 漏洞描述 Relevant Link: http://joychou.org/in ...

  5. Linux下pdf阅读器推荐

    由于需要在pdf文件上做标记,所以自带的文档查看器根本满足了需求,之前去网上查了查,Okular评价挺高,就安装了一个,确实能基本满足我的需求,但是 1.界面感觉还是不太友好,书签栏一直在那. 2.而 ...

  6. Oracle 数据类型

    类型 含义 CHAR(length) 存储固定长度的字符串.参数length指定了长度,如果存储的字符串长度小于length,用空格填充.默认长度是1,最长不超过2000字节. VARCHAR2(le ...

  7. CF 115B Lawnmower(贪心)

    题目链接: 传送门 Lawnmower time limit per test:2 second     memory limit per test:256 megabytes Description ...

  8. PHP之:PHP编程效率的20个要点

    [导读] 用单引号代替双引号来包含字符串,这样做会更快一些.因为PHP会在双引号包围的字符串中搜寻变量,单引号则 不会,注意:只有echo能这么做,它是一种可以把多个字符串当作参数的“函数” 用单引号 ...

  9. K米测评

    第一部分 调研,评测 K米APP使用体验 从小五音不全,所以KTV这类地方我是能不去就不去的,更别说为了点个歌去下个APP,所以K米是我第一个点歌类APP.说说第一次上手的体验吧,APP颜值一般吧,U ...

  10. TreeMap按照key排序

    package test.tool.gui.common; import java.util.Comparator; import java.util.TreeMap; public class Te ...