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

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. ElasticSearch Document API

    删除索引库 可以看到id为1的索引库不见了 这里要修改下配置文件 slave1,slave2也做同样的操作,在这里就不多赘述了. 这个时候记得要重启elasticseach才能生效,怎么重启这里就不多 ...

  2. springboot根据不同的条件创建bean,动态创建bean,@Conditional注解使用

    这个需求应该也比较常见,在不同的条件下创建不同的bean,具体场景很多,能看到这篇的肯定懂我的意思. 倘若不了解spring4.X新加入的@Conditional注解的话,要实现不同条件创建不同的be ...

  3. JS修改属性,六种数据类型

    JS修改属性 一般修改单个属性是通过JS修改的,比较方便.改多个属性通过css样式改更方便. 1.特殊:通过JS修改包含"-"符号的属性,例如margin-top // 特殊 修改 ...

  4. python 编写远程连接服务器脚本

    import paramiko client = paramiko.SSHClient()client.set_missing_host_key_policy(paramiko.AutoAddPoli ...

  5. 自动化运维工具 SaltStack 在云计算环境中的实践

    http://www.talkwithtrend.com/Article/218473

  6. Hive启动异常

    [root@host ~]# hivewhich: no hbase in (/root/app/apache-maven-3.5.2/bin:/usr/local/sbin:/usr/local/b ...

  7. 自定义BeanUtils

    package com.icil.booking.service.util; import java.math.BigDecimal; import java.text.ParseException; ...

  8. leetcode405

    public class Solution { string ConverToHex(string bit) { var s = ""; switch (bit) { " ...

  9. 使用MATPLOTLIB 制图(小图)

    import numpy as np import pandas as pd import matplotlib.pyplot as plt data = pd.read_csv('D:\\myfil ...

  10. 使用django + celery + redis 异步发送邮件

    参考:http://blog.csdn.net/Ricky110/article/details/77205291 环境: centos7  +  python3.6.1 + django2.0.1  ...