现象:

编写了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. Atitit swt 4.3 4.4 4.5 新特性java attilax总结

    Atitit swt 4.3 4.4 4.5 新特性java attilax总结 1. 4.5 Release - June 3, 20151 1.1. Older Releases1 2. SWT  ...

  2. 从头认识Spring-2.4 基于java的标准注解装配-@Inject-限定器@Named

    这一章节我们来讨论一下基于java的标准注解装配标签@Inject的限定器@Named. 1.domain 蛋糕类: package com.raylee.my_new_spring.my_new_s ...

  3. codeforces #364d As Fast As Possible

    题意:一群学生,要到离这里为l的地方去.有一辆车,车只有k个座位.人和车的速度分别v1,v2,问你所有人到达的最小时间. 思路:数学题.最小时间就是要求所有同学同时到达.每个同学最多上一次车.那么显然 ...

  4. nginx 常见参数以及重定向参数配置

    nginx 各参数翻译,作用 $arg_PARAMETER #这个变量包含GET请求中,如果有变量PARAMETER时的值. $args #这个变量等于请求行中(GET请求)的参数,例如foo=123 ...

  5. 不可忽略的apache 的 Keep Alive

    转载链接:http://hi.baidu.com/jx_iben/item/d5fe91feed74495ec9f337f1 在网页开发过程中,Keep-Alive是HTTP协议中非常重要的一个属性. ...

  6. 设计模式之前之UML

    UML,让系统可视化,让规格和设计文档化的表现方法.下面来简单介绍一下这个UML.

  7. jsonp 小结

    JSONP是JSON with Padding的略称. 它允许在服务器端集成Script tags返回至客户端,通过javascript callback的形式实现跨域访问(这仅仅是JSONP简单的实 ...

  8. 工具类之Condition

    再次看到Condition,第一感觉还是觉得它和Mutex的功能是一样的,没必要存在.心里这么想,其实自己也知道怎么可能多余呢?老老实实的再分析一下代码,这次一定要把理解出来的内容记下来!都怪平时写代 ...

  9. LINQ to Tree - A Generic Technique for Querying Tree-like Structures,包含遍历WPF VisualTree

    https://www.codeproject.com/Articles/62397/LINQ-to-Tree-A-Generic-Technique-for-Querying-Tree#generi ...

  10. Node-Webkit - package.json - 参数设置

    必填: main :(string)APP的主入口,指定一个html文件,如:main:"index.htm". name :(string)APP的名称,必须具有唯一性. 例子: ...