Для службы Self-host WCF, созданной WebHttpBinding, мы могли бы использовать следующий код для включения поддержки CORS.
См.
using System;
using System.Collections.Generic;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Configuration;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Web;
Расширение поведения конечной точки.
public class CustomHeaderMessageInspector : IDispatchMessageInspector
{
Dictionary<string, string> requiredHeaders;
public CustomHeaderMessageInspector(Dictionary<string, string> headers)
{
requiredHeaders = headers ?? new Dictionary<string, string>();
}
public object AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, IClientChannel channel, InstanceContext instanceContext)
{
return null;
}
public void BeforeSendReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
{
var httpHeader = reply.Properties["httpResponse"] as HttpResponseMessageProperty;
foreach (var item in requiredHeaders)
{
httpHeader.Headers.Add(item.Key, item.Value);
}
}
}
public class CustomContractBehaviorAttribute : BehaviorExtensionElement, IEndpointBehavior
{
public override Type BehaviorType => typeof(CustomContractBehaviorAttribute);
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
var requiredHeaders = new Dictionary<string, string>();
requiredHeaders.Add("Access-Control-Allow-Origin", "*");
requiredHeaders.Add("Access-Control-Max-Age", "1728000");
requiredHeaders.Add("Access-Control-Request-Method", "POST,GET,PUT,DELETE,OPTIONS");
requiredHeaders.Add("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization, Pragma, Cache-Control");
endpointDispatcher.DispatchRuntime.MessageInspectors.Add(new CustomHeaderMessageInspector(requiredHeaders));
}
public void Validate(ServiceEndpoint endpoint)
{
}
protected override object CreateBehavior()
{
return new CustomContractBehaviorAttribute();
}
}
Примените его в конечной точке службы.
<endpointBehaviors>
<behavior name="EndpBehavior">
<webHttp/>
<CorsBehavior />
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="ServiceBehavior" name="YourNamespace.MathService">
<endpoint address="http://localhost:8181/MathService" binding="webHttpBinding"
contract="YourNamespace.IMathService" behaviorConfiguration="EndpBehavior"/>
</service>
</services>
<extensions>
<behaviorExtensions>
<add name="CorsBehavior" type="YourNamespace.CustomContractBehaviorAttribute, YourNamespace" />
</behaviorExtensions>
</extensions>
</system.serviceModel>
Клиент.
//10.157.13.70 is the host that runs the Winform application.
var serviceuri = "http://10.157.13.70:8181/MathService/add/34";
$.ajax({
method:"Get",
url:serviceuri,
//contentType:"application/x-www-form-urlencoded",
success:function(data){
console.log(data);
}
}).done(function(data){
console.log(data);
}).fail(function(jqxhr,textstatus,err){
console.log(err);
})
Результат.
![enter image description here](https://i.stack.imgur.com/x1yil.png)
Не стесняйтесь, дайте мне знать, если проблема все еще существует.