现象:

编写了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. zabbix api调用

    zabbix api调用 api能干什么 Zabbix API allows you to programmatically retrieve and modify the configuration ...

  2. Active Directory的基本概念

    前言 本文是面对准备加入Active Directory编程的初学者的一份文章,主要是讲解Active Directory(活动目录)的一些概念和相关知识.这篇文章本来是不想写下来的,因为概念性内容的 ...

  3. listView的异步加载数据

    1 public class MainActivity extends Activity { 2 3 private ListView listView; 4 private ArrayList< ...

  4. Rocchio算法

    一.引子 查询扩展(Query Expansion)是信息检索领域的一个重要话题. 一方面.用户本身可能会出错,他会输入一些错别字,比方把"冯小刚",错写成"冯晓刚&qu ...

  5. Java并发编程(一)学习大纲

    (一)学习大纲 (二)线程与并发编程的概念 (三)线程安全.原子操作.复合操作.竞态条件.加锁机制(内置锁.重入) (四)对象的共享:可见性.失效数据.非原子的64位操作,加锁与可见性,volatil ...

  6. 4.关于QT中的QFile文件操作,QBuffer,Label上加入QPixmap,QByteArray和QString之间的差别,QTextStream和QDataStream的差别,QT内存映射(

     新建项目13IO 13IO.pro HEADERS += \ MyWidget.h SOURCES += \ MyWidget.cpp QT += gui widgets network CON ...

  7. centos7.0安装redis扩展

    1.下载 下载地址:https://github.com/phpredis/phpredis/ 文件名:phpredis-develop.zip 文件下载成功后,上传至/usr/local 2.安装 ...

  8. 【CodeM初赛A轮】D 分解质因数+暴力

    题目描述树链是指树里的一条路径.美团外卖的形象代言人袋鼠先生最近在研究一个特殊的最长树链问题.现在树中的每个点都有一个正整数值,他想在树中找出最长的树链,使得这条树链上所有对应点的值的最大公约数大于1 ...

  9. XmlDocument.selectNodes() and selectSingleNode()的xpath的学习资料

    Xpath网页: http://www.w3school.com.cn/xpath/xpath_syntax.asp XDocument.parse(string)类似于XmlDocument.loa ...

  10. HTML元素嵌套关系