using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http.Filters;

namespace MBT.WebKit.Filter
{
/// <summary>
/// 跨域过滤器
/// author:cza
/// date:2018-08-20
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class OriginWebAttribute : Attribute //: ActionFilterAttribute
{
//存储key的,未用到
public string AttributeKey = string.Empty;
public OriginWebAttribute()
{

}

/// <summary>
/// 跨域返回消息头的判断
/// author:cza
/// date:2018-08-20
/// </summary>
/// <param name="actionContext"></param>
public void OriginActionExecuted(System.Web.Http.Controllers.HttpActionContext actionContext) //System.Web.Http.Controllers.HttpControllerContext ControllerContext
{

System.Web.Http.Routing.IHttpRouteData data = actionContext.ControllerContext.RouteData;
//针对controller
var allowAnonymous = actionContext.ControllerContext.ControllerDescriptor.ControllerType.CustomAttributes.SingleOrDefault(m => m.AttributeType.Name == typeof(OriginWebAttribute).Name);
if (allowAnonymous == null)
{
//针对某个方法
Type controllerType = actionContext.ControllerContext.ControllerDescriptor.ControllerType.Assembly.GetTypes().Where(m => m.Name.ToLower() == data.Values["Controller"].ToString().ToLower() + "controller").FirstOrDefault();
var attributes = controllerType.GetMethods().Where(m => m.Name.ToLower() == data.Values["Action"].ToString().ToLower()).FirstOrDefault();

var allowAnonymousMethods = attributes.CustomAttributes.SingleOrDefault(m => m.AttributeType.Name == typeof(OriginWebAttribute).Name);
if (allowAnonymousMethods == null)
{
return;
}

}

#region 跨域的解决办法增加返回消息头
System.Uri uriReferrer = actionContext.ControllerContext.Request.Headers.Referrer;
if (uriReferrer != null)
{
string Origin = uriReferrer.Scheme + "://" + uriReferrer.Host;
int Hostport = uriReferrer.Port;
if (Hostport != 80 && Hostport != 443)
{
Origin = Origin + ":" + Hostport;
}
//没有返回Response消息头的话,不要返回,因为reponse为null的话,证明异常,会走全局捕获。
if (actionContext.Response != null)
{
//var package = PackageKit.GetResponsePackage<string>(null, 301, "");
//string json = JsonConvert.SerializeObject(package);
//actionContext.Response = new System.Net.Http.HttpResponseMessage();
//StringContent Content = new StringContent(json, Encoding.GetEncoding("UTF-8"), "application/json");
//actionContext.Response.StatusCode = HttpStatusCode.OK;
//actionContext.Response.Content = Content;

//授权的请求域名
actionContext.Response.Headers.Add("Access-Control-Allow-Origin", Origin);
actionContext.Response.Headers.Add("Access-Control-Allow-Methods", "*"); //GET,POST,PUT,DELETE,OPTIONS
actionContext.Response.Headers.Add("Access-Control-Allow-Headers", "x-requested-with");
actionContext.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
}

}
#endregion
}
}
}

然后在ApiController或对应的方法加上这个自定义属性就可以了

Mvcapi解决H5请求接口跨域问题的更多相关文章

  1. axios解决调用后端接口跨域问题

    vue-cli通过是本地代理的方式解决接口跨域问题的.但是在vue-cli的默认项目配置中这个代理是没有配置的,如果现在项目中使用,必须手动配置config/index.js文件 ... proxyT ...

  2. 解决ajax请求cors跨域问题

    ”已阻止跨源请求:同源策略禁止读取位于 ***** 的远程资源.(原因:CORS 头缺少 'Access-Control-Allow-Origin').“ ”已阻止跨源请求:同源策略禁止读取位于 ** ...

  3. jQuery解决ajax请求的跨域问题

    这两天工作中频繁的遇到JS的跨域问题,都通过绕开ajax请求的方式.特地百度了一下,把跨域问题解决了.在这分析一下 首先贴上js的页面代码: <html> <head> < ...

  4. 【Vue+Node】解决axois请求数据跨域问题

    项目基于Vue前端+Node后台,启动两个服务,请求数据时,端口不一致造成跨域报错: (No 'Access-Control-Allow-Origin' header is present on th ...

  5. JAVA联调接口跨域解决办法

    JAVA联调接口跨域解决办法 第一种代码: HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1,HttpStatus. ...

  6. Vue的学习总结之---Vue项目 前后端分离模式解决开发环境的跨域问题

    原文:https://blog.csdn.net/localhost_1314/article/details/83623526 在前后端分离的web开发中,我们与后台联调时,会遇到跨域的问题. 比如 ...

  7. odoo接口跨域问题

    odoo Controller接口开发 POST请求的跨域问题解决方法 1.odoo Controller接口开发,前端在请求的时候会发生跨域问题,报错信息如下:Function declared a ...

  8. 前端总结·基础篇·JS(四)异步请求及跨域方案

    前端总结系列 前端总结·基础篇·CSS(一)布局 前端总结·基础篇·CSS(二)视觉 前端总结·基础篇·CSS(三)补充 前端总结·基础篇·JS(一)原型.原型链.构造函数和字符串(String) 前 ...

  9. Vue-cli proxyTable 解决开发环境的跨域问题

    Vue-cli proxyTable 解决开发环境的跨域问题 proxyTable: { '/list': { target: 'http://api.xxxxxxxx.com', pathRewri ...

随机推荐

  1. 借助ADB冻结与卸载Android系统应用(免ROOT)

    背景: 我妈的手机饱受系统应用广告推送之苦,每天都能在通知栏里收到好几条广告.为了给她个清净,本篇博文应运而生. 目标: 卸载安卓系统应用 所用工具: 硬件:我妈的手机(魅蓝5) PC端:Minima ...

  2. .NET混合开发解决方案6 检测是否已安装合适的WebView2运行时

    系列目录     [已更新最新开发文章,点击查看详细] 长青版WebView2运行时将作为Windows 11操作系统的一部分包含在内.但是在Windows 11之前(Win10.Win8.1.Win ...

  3. GO 语言入门(一)

    GO 语言入门(一) 本文写于 2020 年 1 月 18 日 Go 由 Google 工程师 Robert Griesemer,Rob Pike 和 Ken Thompson 设计的一门编程语言,第 ...

  4. 思科,华为l2tp组网,家庭宽带,公司内网数据分离

    拓扑 简介 办公网使用专线接入,拥有固定IP地址,网络出口使用防火墙做NAT,下联交换机接入服务器,办公电脑等,旁挂思科路由器做L2TP LNS 家庭宽带使用ADSL线路,华为路由器做拨号设备与DHC ...

  5. idea maven 依赖还原不上的问题 method <init>()V not found

    问题 还原项目依赖的时候报错: java.lang.RuntimeException: org.codehaus.plexus.component.repository.exception.Compo ...

  6. 提升站点SEO的7个建议

    1.使用HTTPS 谷歌曾发公告表示,使用安全加密协议(HTTPS),是搜索引擎排名的一项参考因素. 所以,在域名相同情况下,HTTPS站点比HTTP站点,能获得更好的排名. 在网络渠道分发或合作上, ...

  7. vue大型电商项目尚品汇(前台篇)day02

    现在正式回归,开始好好做项目了,正好这一个项目也开始慢慢的开始起色了,前面的准备工作都做的差不多了. 而且我现在也开始慢慢了解到了一些项目才开始需要的一些什么东西了,vuex.router这些都是必备 ...

  8. PKUSC2022 游记

    PKUSC2022 游记 Day1 上午随便看了点题,感觉没看什么题就开考了. 开考之后先看 T1,发现 T1 好像不是那么简单. T1 : 九条可怜有两个账号,她每次都会打 \(\rm rating ...

  9. 协议层安全相关《http请求走私与CTF利用》

    0x00 前言 最近刷题的时候多次遇到HTTP请求走私相关的题目,但之前都没怎么接触到相关的知识点,只是在GKCTF2021--hackme中使用到了 CVE-2019-20372(Nginx< ...

  10. 《Effective C++》阅读总结(四): 设计、声明与实现

    第四章: 设计与声明 18. 让接口更容易被正确使用,不易被误用 将你的class的public接口设计的符合class所扮演的角色,必要时不仅对传参类型限制,还对传参的值域进一步限制. 19. 设计 ...