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

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. js实现复选框的全选和全不选

    <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content ...

  2. Visual Studio自动添加头部注释

    VS2013 自动添加头部注释 1.找到VS2013的安装目录 下文以安装目录 C:\Program Files (x86)\Microsoft Visual Studio 12.0 为例 2.修改C ...

  3. java 调用apache.commons.codec的包简单实现MD5加密

    转自:https://blog.csdn.net/mmd1234520/article/details/70210002/ import java.security.MessageDigest; im ...

  4. as3 单例的不常见写法

    方法一:(显式允许new一次) package { import flash.errors.IllegalOperationError; import flash.events.EventDispat ...

  5. Nexus使用

    Nexus使用: Nexus的默认登录账户:admin,密码:admin123. 以下为步骤说明: 1.右上角->login 2.左菜单->security->user->ad ...

  6. Winform-图片上传

    1.界面上拖个.pictureBox(pictureBox1) //上传点击按钮 private void button1_Click(object sender, EventArgs e) { Op ...

  7. 趣味编程:FizzBuzz(Kotlin版)

    fun toFizzBuzzIf(n: Int) = if (n % 3 == 0 && n % 5 == 0) "FizzBuzz" else if (n % 3 ...

  8. 给vim编辑器自动添加行号

    1.只改变当前用户的vim 在~目录下  vim .vimrc添加一行 set number 即可(普通用户权限即可) 2. 改变所有用户的vim 打开文件 /etc/vimrc 添加一行 set n ...

  9. clusterProfiler包

    1)enrichGO:(GO富集分析) 描述:GO Enrichment Analysis of a gene set. Given a vector of genes, this function ...

  10. HttpClient 发送 HTTP、HTTPS

    首先说一下该类中需要引入的 jar 包,apache 的 httpclient 包,版本号为 4.5,如有需要的话,可以引一下.     代码 import org.apache.commons.io ...