WCF REST开启Cors 解决 No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 405.
现象:
编写了REST接口:
[ServiceContract]
public interface IService1
{ [OperationContract]
[WebInvoke(UriTemplate = "/TestMethod", Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json
)]
string TestMethod(CompositeType value); }
数据契约
[DataContract]
public class CompositeType
{
bool boolValue = true;
string stringValue = "Hello "; [DataMember]
public bool BoolValue
{
get { return boolValue; }
set { boolValue = value; }
} [DataMember]
public string StringValue
{
get { return stringValue; }
set { stringValue = value; }
}
}
服务实现
public class Service1 : IService1
{
public string TestMethod(CompositeType value)
{
return string.Format("You entered: {0}", value.StringValue);
}
}
ajax调用
$(document).ready(function () {
$("button").click(function () {
alert("clicked");
var data = $("#txt").val();
var postdata = {};
var data_obj = {"BoolValue" : "true" , "StringValue": data}
postdata["value"] = data_obj;
var url = "https://tmdev01.tm00.com/testwcf/service1.svc/TestMethod";
$.ajax({
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postdata),
dataType: "json",
success: function(data) {console.log(data);},
error: function(a,b,c) {console.log(a);}
});
});
});
报错:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 405.
方法1:
全局请求拦截,处理OPTION谓词
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "http://localhost");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE"); HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
方法2:
定义跨域资源共享相关常量
class CorsConstants
{
internal const string Origin = "Origin";
internal const string AccessControlAllowOrigin = "Access-Control-Allow-Origin";
internal const string AccessControlRequestMethod = "Access-Control-Request-Method";
internal const string AccessControlRequestHeaders = "Access-Control-Request-Headers";
internal const string AccessControlAllowMethods = "Access-Control-Allow-Methods";
internal const string AccessControlAllowHeaders = "Access-Control-Allow-Headers";
internal const string PreflightSuffix = "_preflight_";
}
创建cors属性
public class CorsEnabledAttribute : Attribute, IOperationBehavior
{
public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
{
} public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
{
} public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
{
} public void Validate(OperationDescription operationDescription)
{
}
}
创建自定义消息分发拦截器
class CorsEnabledMessageInspector : IDispatchMessageInspector
{
private List corsEnabledOperationNames; public CorsEnabledMessageInspector(List corsEnabledOperations)
{
this.corsEnabledOperationNames = corsEnabledOperations.Select(o => o.Name).ToList();
} public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
HttpRequestMessageProperty httpProp = (HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];
object operationName;
request.Properties.TryGetValue(WebHttpDispatchOperationSelector.HttpOperationNamePropertyName, out operationName);
if (httpProp != null && operationName != null && this.corsEnabledOperationNames.Contains((string)operationName))
{
string origin = httpProp.Headers[CorsConstants.Origin];
if (origin != null)
{
return origin;
}
} return null;
} public void BeforeSendReply(ref Message reply, object correlationState)
{
string origin = correlationState as string;
if (origin != null)
{
HttpResponseMessageProperty httpProp = null;
if (reply.Properties.ContainsKey(HttpResponseMessageProperty.Name))
{
httpProp = (HttpResponseMessageProperty)reply.Properties[HttpResponseMessageProperty.Name];
}
else
{
httpProp = new HttpResponseMessageProperty();
reply.Properties.Add(HttpResponseMessageProperty.Name, httpProp);
} httpProp.Headers.Add(CorsConstants.AccessControlAllowOrigin, origin);
}
}
}
class EnableCorsEndpointBehavior : IEndpointBehavior
{
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
} public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
} public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
List corsEnabledOperations = endpoint.Contract.Operations
.Where(o => o.Behaviors.Find() != null)
.ToList();
endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new CorsEnabledMessageInspector(corsEnabledOperations));
} public void Validate(ServiceEndpoint endpoint)
{
}
}
class PreflightOperationBehavior : IOperationBehavior
{
private OperationDescription preflightOperation;
private List allowedMethods; public PreflightOperationBehavior(OperationDescription preflightOperation)
{
this.preflightOperation = preflightOperation;
this.allowedMethods = new List();
} public void AddAllowedMethod(string httpMethod)
{
this.allowedMethods.Add(httpMethod);
} public void AddBindingParameters(OperationDescription operationDescription, BindingParameterCollection bindingParameters)
{
} public void ApplyClientBehavior(OperationDescription operationDescription, ClientOperation clientOperation)
{
} public void ApplyDispatchBehavior(OperationDescription operationDescription, DispatchOperation dispatchOperation)
{
dispatchOperation.Invoker = new PreflightOperationInvoker(operationDescription.Messages[1].Action, this.allowedMethods);
} public void Validate(OperationDescription operationDescription)
{
}
}
class PreflightOperationInvoker : IOperationInvoker
{
private string replyAction;
List allowedHttpMethods; public PreflightOperationInvoker(string replyAction, List allowedHttpMethods)
{
this.replyAction = replyAction;
this.allowedHttpMethods = allowedHttpMethods;
} public object[] AllocateInputs()
{
return new object[1];
} public object Invoke(object instance, object[] inputs, out object[] outputs)
{
Message input = (Message)inputs[0];
outputs = null;
return HandlePreflight(input);
} public IAsyncResult InvokeBegin(object instance, object[] inputs, AsyncCallback callback, object state)
{
throw new NotSupportedException("Only synchronous invocation");
} public object InvokeEnd(object instance, out object[] outputs, IAsyncResult result)
{
throw new NotSupportedException("Only synchronous invocation");
} public bool IsSynchronous
{
get { return true; }
} Message HandlePreflight(Message input)
{
HttpRequestMessageProperty httpRequest = (HttpRequestMessageProperty)input.Properties[HttpRequestMessageProperty.Name];
string origin = httpRequest.Headers[CorsConstants.Origin];
string requestMethod = httpRequest.Headers[CorsConstants.AccessControlRequestMethod];
string requestHeaders = httpRequest.Headers[CorsConstants.AccessControlRequestHeaders]; Message reply = Message.CreateMessage(MessageVersion.None, replyAction);
HttpResponseMessageProperty httpResponse = new HttpResponseMessageProperty();
reply.Properties.Add(HttpResponseMessageProperty.Name, httpResponse); httpResponse.SuppressEntityBody = true;
httpResponse.StatusCode = HttpStatusCode.OK;
if (origin != null)
{
httpResponse.Headers.Add(CorsConstants.AccessControlAllowOrigin, origin);
} if (requestMethod != null && this.allowedHttpMethods.Contains(requestMethod))
{
httpResponse.Headers.Add(CorsConstants.AccessControlAllowMethods, string.Join(",", this.allowedHttpMethods));
} if (requestHeaders != null)
{
httpResponse.Headers.Add(CorsConstants.AccessControlAllowHeaders, requestHeaders);
} return reply;
}
}
给接口增加 cors属性标记
[ServiceContract]
public interface IService1
{ [OperationContract]
[WebInvoke(UriTemplate = "/TestMethod", Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json
),CorsEnabled]
string TestMethod(CompositeType value); }
CORS详细说明:https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
WCF REST开启Cors 解决 No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. The response had HTTP status code 405.的更多相关文章
- java、ajax 跨域请求解决方案('Access-Control-Allow-Origin' header is present on the requested resource. Origin '请求源' is therefore not allowed access.)
1.情景展示 ajax调取java服务器请求报错 报错信息如下: 'Access-Control-Allow-Origin' header is present on the requested ...
- 跨域问题解决----NO 'Access-Control-Allow-Origin' header is present on the requested resource.Origin'http://localhost:11000' is therfore not allowed access'
NO 'Access-Control-Allow-Origin' header is present on the requested resource.Origin'http://localhost ...
- Failed to load http://wantTOgo.com/get_sts_token/: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fromHere.com' is therefore not allowed access.
Failed to load http://wantTOgo.com/get_sts_token/: No 'Access-Control-Allow-Origin' header is presen ...
- No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
一.什么是跨域访问 举个栗子:在A网站中,我们希望使用Ajax来获得B网站中的特定内容.如果A网站与B网站不在同一个域中,那么就出现了跨域访问问题.你可以理解为两个域名之间不能跨过域名来发送请求或者请 ...
- XMLHttpRequest cannot load ''. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' ' is therefore not allowed access.
ajax跨域 禁止访问! 利用Access-Control-Allow-Origin响应头解决跨域请求
- As.net WebAPI CORS, 开启跨源访问,解决错误No 'Access-Control-Allow-Origin' header is present on the requested resource
默认情况下ajax请求是有同源策略,限制了不同域请求的响应. 例子:http://localhost:23160/HtmlPage.html 请求不同源API http://localhost:228 ...
- Webapi 跨域 解决解决错误No 'Access-Control-Allow-Origin' header is present on the requested resource 问题
首先是web端(http://localhost:53784) 请求 api(http://localhost:81/api/)时出现错误信息: 查看控制台会发现错误:XMLHttpRequest c ...
- has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
前端显示: has been blocked by CORS policy: Response to preflight request doesn't pass access control che ...
- .Net Core 处理跨域问题Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource
网页请求报错: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Or ...
随机推荐
- 为什么阿里巴巴要求谨慎使用ArrayList中的subList方法
GitHub 3.7k Star 的Java工程师成神之路 ,不来了解一下吗? GitHub 3.7k Star 的Java工程师成神之路 ,真的不来了解一下吗? GitHub 3.7k Star 的 ...
- Android开发和Android Studio使用教程
Android studio安装和简单介绍http://www.jianshu.com/p/36cfa1614d23 是时候把Android 项目切换到Android Studio http://ww ...
- Apatar 学习文档
1. Apatar数据集成简介 Apatar是一个开源跨平台数据集成工具,可以安装和运行在任何机器这有一些类型的用户界面.该工具用于启用批处理数据集成和提供简单的用户界面,这样任何人,不仅仅是技术 ...
- Ubuntu配置apache2.4配置虚拟主机遇到的问题
update: 偶然看到了 apache的更新说明,直接贴个地址过来吧. http://httpd.apache.org/docs/2.4/upgrading.html 最近想把web开发目录从/va ...
- Auto Layout之创建布局约束
上篇文章给大家介绍了AutoLayout 的由来及OC中关于AutoLayout 的类.这篇文章将向大家介绍,在iOS 编程中怎样使用Auto Layout 构建布局约束. 创建布局约束 创建布局约束 ...
- DFS应用——找出无向图的割点
[0]README 0.1) 本文总结于 数据结构与算法分析, 源代码均为原创, 旨在 理解 "DFS应用于找割点" 的idea 并用源代码加以实现: 0.2) 必须要事先 做个s ...
- idangerous swiper
最近使用Swipe.js,发现中文的资料很少,试着翻译了一下.能力有限,翻译难免错漏,欢迎指出,多谢! 翻译自:http://www.idangero.us/sliders/swiper/api.ph ...
- Maven插件wro4j-maven-plugin压缩、合并js、css详解
1. 在pom.xml文件中,引入wro4j-maven-plugin插件 <plugin> <groupId>ro.isdc.wro4j</groupId> ...
- Feign-独立使用-实战
目录 写在前面 1.1.1. 短连接API的接口准备 1.1.2. 申明远程接口的本地代理 1.1.3. 远程API的本地调用 写在最后 疯狂创客圈 亿级流量 高并发IM 学习实战 疯狂创客圈 Jav ...
- 学院名单-211院校研招学院-中国教育在线(www.eol.cn)170915164402
[数据结果] 学校数.学院数:112,2657. [数据来源] 中国教育在线(www.eol.cn)211院校研招学院. http://www.eol.cn/html/ky/gxmd/211.shtm ...