我这里只写基本用法以作记录,具体为什么看下面的文章:

http://www.cnblogs.com/landeanfen/p/5177176.html

http://www.cnblogs.com/moretry/p/4154479.html

Nuget:microsoft.aspnet.webapi.cors,安装到WebApi项目上

web.config:

<appSettings>
<add key="cors:allowedMethods" value="*"/>
<add key="cors:allowedOrigin" value="http://localhost:63145"/>
<add key="cors:allowedHeaders" value="*"/>
</appSettings>

/App_Start/WebApiConfig修改一下:

引入命名空间:

using System.Web.Http.Cors;
using System.Configuration;

然后在Register函数里加入这段代码:这样以来就是全部的接口都具有跨域支持

#region 跨域配置
var allowedMethods = ConfigurationManager.AppSettings["cors:allowedMethods"];//跨域支持的请求方式 get,post,put,delete; * 代表所有,多种方式用逗号隔开。
var allowedOrigin = ConfigurationManager.AppSettings["cors:allowedOrigin"];//接受指定域名下的跨域请求,*表示接受任何来源的请求。
var allowedHeaders = ConfigurationManager.AppSettings["cors:allowedHeaders"];// var geduCors = new EnableCorsAttribute(allowedOrigin, allowedHeaders, allowedMethods)
{
SupportsCredentials = true
};
config.EnableCors(geduCors);
#endregion

另一个方法,在Controller上面加特性描述,这样只有这个接口支持跨域:

//[EnableCors(origins: "http://localhost:63145", headers: "*", methods: "GET,POST,PUT,DELETE")]//也可以这样用
public class ChargingController : ApiController
{
/// <summary>
/// api/Charging/GetAllChargingData
/// </summary>
/// <returns></returns>
[HttpGet]
public string GetAllChargingData()
{
//HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent("success", Encoding.GetEncoding("UTF-8"), "application/json") };
//return result; return ToJsonTran.ToJson2("success");
}
}

ToJsonTran是什么:

public class ToJsonTran
{
public static HttpResponseMessage ToJson(Object obj)
{
String str;
if (obj is String || obj is Char)
{
str = obj.ToString();
}
else
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
str = serializer.Serialize(obj);
}
HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json") }; return result;
} public static string ToJson2(Object obj)
{
String str;
if (obj is String || obj is Char)
{
str = obj.ToString();
}
else
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
str = serializer.Serialize(obj);
}
return str;
}
}

页面上面的js测试跨域:

<script>
jQuery.support.cors = true;
var ApiUrl = "http://localhost:58068/";
$(function () {
$.ajax({
type: "get",
url: ApiUrl + "api/Charging/GetAllChargingData",
data: {},
success: function (data, status) {
debugger;
if (status == "success") {
$("#div_test").html(data);
}
},
error: function (e) {
debugger;
$("#div_test").html("Error");
},
complete: function () { } });
});
</script> 测试结果:<div id="div_test"></div>

POST请求:

function test1() {
$.ajax({
type: "POST",
url: ApiUrl + "OfficialStoryInfo/GetJsonPDataByID",
contentType: 'application/json',
data: JSON.stringify({ ID: 711, callback: "" }),
success: function (d, status) {
debugger;
if (status == "success") {
var StoryInfo = $.parseJSON(d).Data;
if (StoryInfo != null && StoryInfo != undefined) {
var Name = StoryInfo.Name;
var Description = StoryInfo.Description;
document.title = Name;
$("meta[name='apple-mobile-web-app-title']").attr('content', Name);
$("#div_test").html(Description);
}
}
},
error: function (e) {
debugger;
$("#div_test").html("Error");
},
complete: function () { } });
}

这里的post请求,注意 contentType 和 data 里的 JSON.stringify() ,这样后台Api接口可以使用 dynamic 参数接收。注意看开头引用的那两篇文章。

注意:jQuery.support.cors = true;因为有些浏览器不支持js跨域,加上这句。

最近又发现了一个方法,只不过我还没试过,如下:

在web.config的<system.webServer>节点下面加入配置:

<!--跨域配置-->

<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Max-Age" value="30"/>
<add name="Access-Control-Allow-Methods" value="GET,POST,OPTIONS"/>
<add name="Access-Control-Allow-Headers" value="Content-Type, Accept" />
</customHeaders>
</httpProtocol>

.NET中CORS跨域访问WebApi的更多相关文章

  1. Asp.Net WebApi 启用CORS跨域访问指定多个域名

    1.后台action指定 EnableCors指定可访问的域名多个,使用逗号隔开 //支持客户端凭据提交,指定多个域名,使用逗号隔开 [EnableCors("http://localhos ...

  2. Asp.Net WebApi+Microsoft.AspNet.WebApi.Core 启用CORS跨域访问

    WebApi中启用CORS跨域访问 1.安装 Nugget包Microsoft.AspNet.WebApi.Cors This package contains the components to e ...

  3. Spring Boot 2中对于CORS跨域访问的快速支持

    原文:https://www.jianshu.com/p/840b4f83c3b5 目前的程序开发,大部分都采用前后台分离.这样一来,就都会碰到跨域资源共享CORS的问题.Spring Boot 2 ...

  4. spring boot / cloud (六) 开启CORS跨域访问

    spring boot / cloud (六) 开启CORS跨域访问 前言 什么是CORS? Cross-origin resource sharing(跨域资源共享),是一个W3C标准,它允许你向一 ...

  5. Springboot CORS跨域访问

    Springboot CORS跨域访问 什么是跨域 浏览器的同源策略限制: 它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响.可以说Web是构建在同源策略基础 ...

  6. SpringBoot学习(3)-SpringBoot添加支持CORS跨域访问

    SpringBoot学习(3)-SpringBoot添加支持CORS跨域访问 https://blog.csdn.net/yft_android/article/details/80307672

  7. 浏览器跨域访问WebApi

      webapi地址:wapapi.ebcbuy.com web地址:wapweb.ebcbuy.com   在默认情况下这两个域名属于两个不同的域,他们之间的交互存在跨域的问题,但因为他们都同属于一 ...

  8. Spring MVC 4.2 CORS 跨域访问

    跨站 HTTP 请求(Cross-site HTTP request)是指发起请求的资源所在域不同于该请求所指向资源所在的域的 HTTP 请求.比如说,域名A(http://domaina.examp ...

  9. 在IE浏览器中iframe跨域访问cookie/session丢失的解决办法

    单点登录需要在需要进入的子系统B中添加一个类,用于接收A系统传过来的参数: @Action(value = "outerLogin", results = { @Result(na ...

随机推荐

  1. JavaScript的灵活应用

    1.查找数组的最大值和最小值 (1) Math.max.qpply(null,array); Math.min.qpply(null,array); (2) eval("Math.max(& ...

  2. Python Json序列化与反序列化

    在python中,序列化可以理解为:把python的对象编码转换为json格式的字符串,反序列化可以理解为:把json格式字符串解码为python数据对象.在python的标准库中,专门提供了json ...

  3. Android SDK的安装与环境配置

    一.Android SDK工具下载.安装 Android SDK工具下载:http://www.androiddevtools.cn/ SDK下载页面如下,由于电脑Windows系统所以下载的Wind ...

  4. git常用命令,冲突

    使用多个仓库git push cangkuming fenzhiming删除远程仓库 git push 远程仓库名 :删除目标分支 # 需要先删除本地目标分支 git pull <远程主机名&g ...

  5. create a bootable USB stick on Ubuntu

    https://tutorials.ubuntu.com/tutorial/tutorial-create-a-usb-stick-on-ubuntu?_ga=2.141187314.17572770 ...

  6. Python selenium的js扩展实现

    python写的数据采集,对一般有规律的页面用 urllib2 + BeautifulSoup + 正则就可以搞定. 但是有些页面的内容是通过js生成,或者通过js跳转的,甚至js中还加入几道混淆机制 ...

  7. C# EF 基础操作

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  8. Procedure-Function oracle

    说明:SQL语言共分为四大类:数据查询语言DQL,数据操纵语言DML, 数据定义语言DDL,数据控制语言DCL. 0.调试 点击procedure名,右键选择调试.即可进入调试模式.找到procedu ...

  9. UI5-文档-2.2-使用SAP Web IDE开发应用程序

    SAP Web IDE是一种基于Web的开发环境,它是为使用最新的创新开发SAPUI5复杂的应用程序.开发和扩展SAP Fiori应用程序.开发移动混合应用程序以及使用插件和模板扩展SAP Web I ...

  10. 删除数据恢复数据语句 Oracle

    SELECT * FROM TBL_DZYJ_GEORELICSINFO AS OF TIMESTAMP TO_TIMESTAMP('2017-5-8 9:00:00','YYYY-MM-DD HH: ...