现象:

编写了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.的更多相关文章

  1. 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 ...

  2. 跨域问题解决----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 ...

  3. 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 ...

  4. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

    一.什么是跨域访问 举个栗子:在A网站中,我们希望使用Ajax来获得B网站中的特定内容.如果A网站与B网站不在同一个域中,那么就出现了跨域访问问题.你可以理解为两个域名之间不能跨过域名来发送请求或者请 ...

  5. 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响应头解决跨域请求

  6. 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 ...

  7. Webapi 跨域 解决解决错误No 'Access-Control-Allow-Origin' header is present on the requested resource 问题

    首先是web端(http://localhost:53784) 请求 api(http://localhost:81/api/)时出现错误信息: 查看控制台会发现错误:XMLHttpRequest c ...

  8. 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 ...

  9. .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 ...

随机推荐

  1. python unittest不执行"if __name__ == '__main__' "问题(Pycharm)

    问题: 1.selenium导入unittest框架和HtmlReport框架后,HtmlReport不被执行. 2.IDE为Pycharm 假设代码为: from selenium import w ...

  2. 基于JT/T 1078协议设计和开发部标视频服务器

    交通部与2016年10月份推出了JT/T 1078-2016标准,全称是<道路运输车辆卫星定位系统视频通信协议>.该标准将改变以往两客一危车辆的视频监控设备通信协议都是设备厂商私有协议的局 ...

  3. MapReduce源码分析之InputFormat

    InputFormat描述了一个Map-Reduce作业中的输入规范.Map-Reduce框架依靠作业的InputFormat实现以下内容: 1.校验作业的输入规范: 2.分割输入文件(可能为多个), ...

  4. 并行归并排序——MPI

    并行归并排序在程序开始时,会将n/comm_comm个键值分配给每个进程,程序结束时,所有的键值会按顺序存储在进程0中.为了做到这点,它使用了树形结构通信模式.当进程接收到另一个进程的键值时,它将该键 ...

  5. Linux中openmpi配置

    到 http://www.open-mpi.org/ 下载openmpi并解压,事先安装gcc或g++. 我是openmpi-1.6.5,进入解压文件夹,执行 ./configure 这一步执行时间会 ...

  6. Python鸡汤

    标准库 很正确 外部库 有一些风险,可能有bug,可能文档不全,可能长时间未更新. ipython 1 pip 这应该是安装Python后第一个需要的命令 pip install -i -i, --i ...

  7. 在Hierarchy面板隐藏物体

    PlantObjPreview.hideFlags = HideFlags.HideInHierarchy;

  8. github-readme.md-格式

    大标题 大标题一般显示project名,类似html的<h1> 你仅仅要在标题以下跟上=====就可以 中标题 中标题一般显示重点项,类似html的<h2> 你仅仅要在标题以下 ...

  9. (一)unity4.6Ugui中文教程文档-------概要

    大家好,我是孙广东.   转载请注明出处:http://write.blog.csdn.net/postedit/38922399 更全的内容请看我的游戏蛮牛地址:http://www.unityma ...

  10. 【BZOJ3720】Gty的妹子树 块状树

    [BZOJ3720]Gty的妹子树 我曾在弦歌之中听过你,檀板声碎,半出折子戏.舞榭歌台被风吹去,岁月深处尚有余音一缕……Gty神(xian)犇(chong)从来不缺妹子……他来到了一棵妹子树下,发现 ...