现象:

编写了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. Unity3D - 性能优化之Draw Call

    Unity3D - 性能优化之Draw Call 分类: Unity 3D2012-09-13 11:18 1002人阅读 评论(0) 收藏 举报 性能优化引擎测试脚本图形算法 Unity(或者说基本 ...

  2. Unity2D实现人物三连击

    之前写过一个系列<HTML5 2D平台游戏开发>,在此过程中发现有很多知识点没有掌握,而且用纯JavaScript来开发一个游戏效率极低,因为调试与地图编辑都没有可视化的工具,开发起来费时 ...

  3. foxmail 客户端 LOGIN Login error password error

    显示这个错误是我在更换电脑时,将E:\Foxmail 7.2\Storage\15167136106@163.com 账户 移动到新的电脑上,并在新电脑上创建用户,总是报:账户或密码错误 我输入的密码 ...

  4. NPOI 计算单元格高度

    需求 要导出一个Excel,第一行是不定长字符串,合并单元格(A-G)已知,现要计算第一行的高度. 思路 已知,NPOI的宽度单位是1/256个英文字符,在本例中,A列的宽度是2048,即 2048 ...

  5. HDFS源码分析数据块校验之DataBlockScanner

    DataBlockScanner是运行在数据节点DataNode上的一个后台线程.它为所有的块池管理块扫描.针对每个块池,一个BlockPoolSliceScanner对象将会被创建,其运行在一个单独 ...

  6. sublime使用技巧(2)-- 实用插件推荐【持续更新】

    1.Auto semicolon 在括号内输入分号,会自动把光标移到行尾然后再输入分号. 2.DocBlockr 补全注析格式,例如在函数上面输入/** + Enter,就会自动补全函数的注析说明. ...

  7. ThinkPHP3.1URL分发BUG修正

    请先留意以下PHP脚本 PHP脚本A(http://127.0.0.1:8110/test.php): $url = 'http://127.0.0.1:8110/demo.php'; //curl请 ...

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

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

  9. RGBA与半透明背景

    概念 所谓RGBA颜色,就是RGB三原色加ALPHA.在给背景加入颜色的同一时候.提供透明度特性. 用法 background:rgba(90,90, 54, 0.5); 支持情况 Firefox 3 ...

  10. 利用solr6.5,tomcat9.0和centos7.0的搭建

    第一步:去官网下载所需的软件包, jdk1.8   wget http://download.oracle.com/otn-pub/java/jdk/8u131-b11/d54c1d3a095b4ff ...