代码控制跨域:

如何使用:在 Global.asax 对应的控制类中:

protected void Application_BeginRequest()
{

if (CorsFilter.IsOptionstRequest())
{
CorsFilter.AllowCors();
return;
}

}


/// <summary>
/// 允许跨域请求标识
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class CorsAttribute : Attribute
{
public CorsAttribute()
{
this.Enabled = true;
}


/// <summary>
/// 是否启用,默认:true
/// </summary>
public bool Enabled { get; set; }

}


 public class CorsFilter : ActionFilterAttribute
{ public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var request = filterContext.RequestContext.HttpContext.Request;
var response = filterContext.RequestContext.HttpContext.Response; try
{
//判断是否支持跨域
CorsAttribute corsAttribute = null;
corsAttribute = filterContext.Controller.GetType().GetCustomAttributes(typeof(CorsAttribute), true).FirstOrDefault() as CorsAttribute; if (null == corsAttribute)
{
ActionDescriptor actionDescriptor = filterContext.ActionDescriptor;
corsAttribute = (CorsAttribute)actionDescriptor.GetCustomAttributes(typeof(CorsAttribute), true).FirstOrDefault() ??
(CorsAttribute)actionDescriptor.GetCustomAttributes(typeof(CorsAttribute), true).FirstOrDefault(); } if (corsAttribute != null&&corsAttribute.Enabled==true)
{
//添加制定heads
AllowCors();
} }
catch (Exception ex)
{
} base.OnActionExecuting(filterContext);
} /// <summary>
/// 允许跨域请求-注册请求头信息
/// </summary>
public static void AllowCors()
{
var req = HttpContext.Current.Request; //options请求
var originName = req.Headers["Origin"];
string originHost = new Uri(originName).Host; //从配置文件检索放行的跨域domains
var allowCorsDomians=Config.Instance["CORSAllowDomians"]?.Split(",", StringSplitOptions.RemoveEmptyEntries);
if (allowCorsDomians.IsEmpty() || !allowCorsDomians.Contains(originHost))
{
///_logger.Error("444444444444444444444*******"+ allowCorsDomians.ToJsonString()+"$$$$$"+ originHost); return;
} SetResponseHeaders(); if (IsOptionstRequest())
{
HttpContext.Current.Response.End();
HttpContext.Current.Response.Flush();
} return;
} private static void SetResponseHeaders()
{ var req = HttpContext.Current.Request;
var rsp = HttpContext.Current.Response;
var requestHeader = req.Headers; string origin = requestHeader.GetValues("Origin").FirstOrDefault();
Dictionary<string, string> headers = new Dictionary<string, string>(); headers.Add("Access-Control-Allow-Origin", origin);
////headers.Add("Access-Control-Allow-Headers", "Content-Type");
headers.Add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
headers.Add("Access-Control-Allow-Credentials", "true");
string requestHeaders = requestHeader.GetValues("Access-Control-Request-Headers")?.FirstOrDefault();
if (!string.IsNullOrEmpty(requestHeaders))
{
headers.Add("Access-Control-Allow-Headers", requestHeaders);
}
else
{
headers.Add("Access-Control-Allow-Headers", "Content-Type");
} foreach (var item in headers)
{
rsp.Headers.Add(item.Key, item.Value);
}
} /// <summary>
/// 是否是 options 预请求
/// </summary>
/// <returns></returns>
public static bool IsOptionstRequest()
{ var req = HttpContext.Current.Request; var requestHeader = req.Headers; bool result = (req.HttpMethod == "OPTIONS" &&
requestHeader.AllKeys.Contains("Origin") &&
requestHeader.AllKeys.Contains("Access-Control-Request-Method")); return result;
} }

Access-Control-Allow-Origin Header and the ASP.NET Web API

In this article we are going to look at few possible fixes we can apply when we get an error “Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:58018’ is therefore not allowed access.” We get this error when we are trying to get some data from another origin, like an AJAXcall. In this post, we will discuss the solutions for this error in detail and we will also discuss Cross Origin Requests. Here I am going to use Visual Studio 2015, Web API 2. I hope you will like this.

Background

I hosted my Web API in a server, and what that API does is, it will just return the data in JSONformat. But when I try to consume this Web API via an Ajax call, I was getting the error “No ‘Access-Control-Allow-Origin’ header is present on the requested resource”. I solved the same issues in different ways. Here I am going to share those.

Using the Code

I assume that you have created a Web API and hosted it on your server. If you are new to Web API, you can always get some information from here Articles Related To Web API.

We all will have some situations where we need to fetch some data from another domain or another site, right? If it is from the same site, you won’t be facing any issues at all. Like you are calling an Ajax call from the page www.SibeeshPassion.com/Receiver.html to www.SibeeshPassion.com/Sender.html to get the data, here the origin is same, and therefore, you will get the data. What happens is when the sender and receiver is not in the same origin, like you need to get the data from www.Microsoft.com by an Ajax call in www.SibeeshPassion.com/Receiver.html, the browser will not allow you to get the sensitive data from other domain, for the security purpose your browser will return you “No ‘Access-Control-Allow-Origin'.” To overcome this, we have something called Cross-Origin Resource Sharing (CORS). Basically the process of allowing other sites to call your Web API is called CORS. According to W3 Org CORS is a standard which tells the server to allow the calls from other origins given. It is much secured than using JSONP(Previously we had been using JSON for getting the data from other domains.).

Fix To No Access-Control-Allow-Origin Header is Present

We can fix this issue in two ways,

  • By using Microsoft.AspNet.WebApi.Cors
  • By adding header information in Web.config

We will explain both now.

By Using Microsoft.AspNet.WebApi.Cors

To work with this fix, you must include the package By using Microsoft.AspNet.WebApi.Cors from Manage Nuget window.

CORS_In_Manage_NuGet_Package

Now got to App_Start folder from your solution. Then click on the file WebApiConfig.cs, this is the file where we set the configuration for our Web API.

Web_API_Config_Class_File

Then you can add the preceding codes in the static function  Register .

 
 
 var cors = new EnableCorsAttribute("*", "*", "*");
 
            config.EnableCors(cors);
 

If you do this, the CORS will be applied globally for all the Web API controllers you have. This is the easiest way of doing it. Now if you want to see the metadata of  EnableCorsAttribute , you can see find it below.

 
 
 // Summary:
 
        //     Initializes a new instance of the System.Web.Http.Cors.EnableCorsAttribute class.
 
        //
 
        // Parameters:
 
        //   origins:
 
        //     Comma-separated list of origins that are allowed to access the resource. Use
 
        //     "*" to allow all.
 
        //
 
        //   headers:
 
        //     Comma-separated list of headers that are supported by the resource. Use "*" to
 
        //     allow all. Use null or empty string to allow none.
 
        //
 
        //   methods:
 
        //     Comma-separated list of methods that are supported by the resource. Use "*" to
 
        //     allow all. Use null or empty string to allow none.
 
        public EnableCorsAttribute(string origins, string headers, string methods);
 

As it is mentioned, it accepts the parameters origins, headers, methods. Here we pass *   to all the three parameters to make everything to be allowable.

You can also try the same as below in the Register function. Here we are going to apply CORS for a particular controller, which means it will be applied to all the actions in the controller. Before that make sure you have added the preceding code in your WebApiConfig.cs file

 
 
config.EnableCors();
 

And in the API controller, you need to set the origins, headers, methods as preceding.

 
 
using System;
 
using System.Collections.Generic;
 
using System.IO;
 
using System.Linq;
 
using System.Net;
 
using System.Net.Http;
 
using System.Web.Http;
 
using Newtonsoft.Json;
 
using Newtonsoft.Json.Converters;
 
using System.Configuration;
 
using System.Data;
 
using System.Data.SqlClient;
 
using System.Runtime.Serialization;
 
using System.Text;
 
using System.Web;
 
using System.Web.Http.Cors;
 
 
namespace APIServiceApplication.Controllers
 
{
 
 
    [EnableCors(origins: "*", headers: "*", methods: "*")]
 
    public class DefaultController : ApiController
 
    {
 
    }
 
}
 

Make sure that you have added namespace using System.Web.Http.Cors; to use CORS. You can always disable CORS in an action by using [DisableCors].

 
 
namespace APIServiceApplication.Controllers
 
{
 
 
    [EnableCors(origins: "*", headers: "*", methods: "*")]
 
    public class DefaultController : ApiController
 
    {
 
        [DisableCors]
 
        public string XMLData(string id)
 
        {
 
            return "Your requested product" + id;
 
        }
 
    }
 
}
 

Here we have disabled CORS for the action XMLData. And again if you need to apply CORS only in a single action, you can do that as follows.

 
 
namespace APIServiceApplication.Controllers
 
{
 
    public class DefaultController : ApiController
 
    {
 
        [EnableCors(origins: "*", headers: "*", methods: "*")]
 
        public string XMLData(string id)
 
        {
 
            return "Your requested product" + id;
 
        }
 
    }
 
}
 

I hope you are aware of how to enable CORS now.

By Adding Header Information in Web.config

Another fix we can do is that add some tags to our Web.config file.

 
 
<system.webServer>

      <httpProtocol>

        <customHeaders>

          <add name="Access-Control-Allow-Origin" value="*" />

          <add name="Access-Control-Allow-Headers" value="Content-Type" />

          <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS" />

         <add name="Access-Control-Allow-Credentials" value="true" />

        </customHeaders>

      </httpProtocol>

  </system.webServer>
 

As you can see we have added keys with value for the listed items.

  • Access-Control-Allow-Origin (For Origin)
  • Access-Control-Allow-Headers (For Headers)
  • Access-Control-Allow-Methods (For Methods)

Now if you go to your server and check, you can see that all the things are configured perfectly. I have configured my API in my server IIS, so I am going to see my Response Header settings in IIS.

Go to the command window and type inetmgr and click OK, your IIS will be opened shortly, now find your Web API which you have already configured under Default Web Site. Before doing this, please make sure that you have configured IIS in your windows. If you don’t know how to configure, I strongly recommend you to read Configure IIS in Windows.

Configured_Web_API_in_IIS

Go to Features View and double click on HTTP Response Headers under IIS category.

HTTP_Response_Headers_In_IIS

You can see all the settings has been configured there.

HTTP_Response_Headers_Available

That’s all, now if you run your application, you will be able to fetch the data from your Web API.

CORS-跨域问题:Access-Control-Allow-Origin Header and the ASP.NET Web API的更多相关文章

  1. SpringBoot添加Cors跨域配置,解决No 'Access-Control-Allow-Origin' header is present on the requested resource

    目录 什么是CORS SpringBoot 全局配置CORS 拦截器处理预检请求 什么是CORS 跨域(CORS)请求:同源策略/SOP(Same origin policy)是一种约定,由Netsc ...

  2. 通过扩展让ASP.NET Web API支持W3C的CORS规范

    让ASP.NET Web API支持JSONP和W3C的CORS规范是解决"跨域资源共享"的两种途径,在<通过扩展让ASP.NET Web API支持JSONP>中我们 ...

  3. 通过扩展让ASP.NET Web API支持W3C的CORS规范(转载)

    转载地址:http://www.cnblogs.com/artech/p/cors-4-asp-net-web-api-04.html CORS(Cross-Origin Resource Shari ...

  4. CORS 跨域 实现思路及相关解决方案

    本篇包括以下内容: CORS 定义 CORS 对比 JSONP CORS,BROWSER支持情况 主要用途 Ajax请求跨域资源的异常 CORS 实现思路 安全说明 CORS 几种解决方案 自定义CO ...

  5. CORS跨域实现思路及相关解决方案

    本篇包括以下内容: CORS 定义 CORS 对比 JSONP CORS,BROWSER支持情况 主要用途 Ajax请求跨域资源的异常 CORS 实现思路 安全说明 CORS 几种解决方案 自定义CO ...

  6. JavaScript跨域调用、JSONP、CORS与ASP.NET Web API[共8篇]

    [第1篇] 同源策略与JSONP 浏览器是访问Internet的工具,也是客户端应用的宿主,它为客户端应用提供一个寄宿和运行的环境.而这里所说的应用,基本是指在浏览器中执行的客户端JavaScript ...

  7. ajax——CORS跨域调用REST API 的常见问题以及前后端的设置

    RESTful架构是目前比较流行的一种互联网软件架构,在此架构之下的浏览器前端和手机端能共用后端接口. 但是涉及到js跨域调用接口总是很头疼,下边就跟着chrome的报错信息一起来解决一下. 假设:前 ...

  8. jsonp与cors跨域的一些理解(转)

    CORS其实出现时间不短了,它在维基百科上的定义是:跨域资源共享(CORS )是一种网络浏览器的技术规范,它为Web服务器定义了一种方式,允许网页从不同的域访问其资源.而这种访问是被同源策略所禁止的. ...

  9. 在ASP.NET Web API中实现CORS(跨域资源共享)

    默认情况下,是不允许网页从不同的域访问服务器资源的,访问遵循"同源"策略的原则. 会遇到如下的报错: XMLHttpRequest cannot load http://local ...

随机推荐

  1. [LeetCode] 543. 二叉树的直径 ☆(递归、数最大深度)

    描述 给定一棵二叉树,你需要计算它的直径长度.一棵二叉树的直径长度是任意两个结点路径长度中的最大值.这条路径可能穿过根结点. 示例 :给定二叉树 1 / \ 2 3 / \ 4 5 返回 3, 它的长 ...

  2. [LeetCode] 437. 路径总和 III ☆☆☆(递归)

    路径总和 III 描述 给定一个二叉树,它的每个结点都存放着一个整数值. 找出路径和等于给定数值的路径总数. 路径不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子 ...

  3. MySQL 5.7的复制架构,在有异步复制、半同步、增强半同步、MGR等的生产中,该如何选择?

    一.生产环境中: 几种复制场景都有存在的价值.下面分别描述一下: 从成熟度上来选择,推荐:异步复制(GTID+ROW) 从数据安全及更高性能上选择:增强半同步 (在这个结构下也可以把innodb_fl ...

  4. CASE WHEN 函数

    --Case函数: --有两种格式: -- 1.简单Case函数. -- 2.Case搜索函数. --1.简单Case函数: -- CASE [COLUMN_NAME] -- WHEN ['条件参数' ...

  5. Docker04-镜像

    目录 镜像介绍 获取镜像 案例:获取 redis 5.0.0的镜像 查询本地镜像 搜索镜像 删除镜像 案例:删除redis:latest镜像 镜像加速 镜像介绍 镜像是Docker的三大核心概念之一. ...

  6. http,socket,进程通信,网络通信(1)

    众所周知,网络通信本质上就是进程间通信,进程间通信有以下常见的通信方式: 1,管道pipe:管道是一种半双工的通信方式,数据只能单向流动,而且只能在具有亲缘关系的进程间使用,进程的亲缘关系通常指父子进 ...

  7. docker里运行cron的要点笔记

    1.如果用精简的apline或debian:stretch-slim创建的docker,里面可能没有cron模块,需要独立安装 apt-get install -y cron 2.docker里面cr ...

  8. java 的任意进制间转换

    直接上代码: public class Main { public static void main(String[] args) { // TODO Auto-generated method st ...

  9. dockerhub下载加速

    curl -sSL https://get.daocloud.io/daotools/set_mirror.sh | sh -s http://f5dad4ec.m.daocloud.io syste ...

  10. hak的使用

    autohotkey简称ahk 它是一款轻量级的脚本语言文件,它可以干任何事情,如做dnf的连发脚本,类似按键精灵的自动化点击,按键自动打开文件一系列事情,文件需要按照ahk自己的语言,实现自定义的脚 ...