【发布时间】:2019-10-27 01:39:14
【问题描述】:
在发布这个问题之前,我已经浏览了很多类似的帖子,但找不到解决方案。
我在 WinForms 应用程序中有一个自托管 WCF 服务。
代码:
[ServiceContract]
public interface IMathService
{
[WebInvoke(Method = "GET",
UriTemplate = "Add/{num1}",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
[OperationContract]
int Add(string num1);
}
public class MathService : IMathService
{
public int Add(string num1)
{
return Convert.ToInt32(num1) + 1;
}
}
public Form1()
{
InitializeComponent();
WebServiceHost testHost = new WebServiceHost(typeof(MathService));
testHost.Open();
}
App.Config:
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="EndpBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="ServiceBehavior" name="S3SelfHost.MathService">
<endpoint address="http://localhost:8181/MathService" binding="webHttpBinding"
contract="S3SelfHost.IMathService" behaviorConfiguration="EndpBehavior"/>
</service>
</services>
</system.serviceModel>
</configuration>
我有一个普通的 html 页面和一个 js 文件,我试图从中调用这个仅在我的本地机器上运行的服务。
JS:
$("#btnAdd").click(function () {
jQuery.support.cors = true;
$.ajax({
type: "POST",
contentType: "application/json; charset=UTF-8; charset-uf8",
url: 'http://localhost:8181/MathService/Add/1',
success: function (data) {
$("#result").val(result);
},
error: function (result) {
alert(result);
}
});
});
如果我直接在浏览器中点击托管 url,那么它会显示正确的结果,但是当我在 js 代码中使用相同的 url 时,它会在控制台中显示以下错误。
在“http://localhost:8181/MathService/Add/1”访问 XMLHttpRequest 来自原点“http://localhost”已被 CORS 策略阻止: 对预检请求的响应未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。
在提琴手响应标头中显示
405 方法不允许
【问题讨论】:
标签: ajax wcf cross-domain self-hosting http-status-code-405