【问题标题】:Access Control Allow Origin issue with WCF serviceWCF 服务的访问控制允许来源问题
【发布时间】:2017-06-12 18:27:20
【问题描述】:
  • 我是 WCF Restful Service 的新手,在 UI 中使用 WCF 项目服务并收到以下错误*

错误 1:- 请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'http://localhost:2021' 不允许访问。

错误 2:- 预检响应包含无效的 HTTP 状态代码 405。

我搜索过谷歌,知道这是 Chrome 的跨域问题。所以我在我的 App.Config 中添加了以下内容。

<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
</customHeaders>
</httpProtocol>
</system.webServer>

并使用以下代码更改方法头。

[OperationContract]
[WebInvoke(Method = "OPTION", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "AddAddressDirectory")]
Task<string> AddAddressDirectory(string aDVM);

我正在使用 SOAP 服务

public string AddAddressDirectory(string model)
{
var aDVMObj = JsonConvert.DeserializeObject<AddressDirectoryViewModel>(model);
var result = _directoryServiceClient.AddAddressDirectory(aDVMObj);
var json = JsonConvert.SerializeObject(result);
return json;
}

我正在从 angularJs 调用该方法。

var _apiPost = function (url, data, success, failure) {
var req = {
url: serviceUrl + url,
method: 'OPTIONS',
headers: {
'Content-Type': "application/json"
},
dataType: "json",
//crossDomain: true,
//processData: true,
data: JSON.stringify(data)
//data: $httpParamSerializer(JSON.stringify(data))
};
$http(req).then(success, function (response) { });
};

【问题讨论】:

    标签: c# angularjs wcf


    【解决方案1】:

    将此添加到您的网络配置文件中:

    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*"/>
        <add name="Access-Control-Allow-Headers" value="X-Requested-With,Content-Type, Accept" />
      </customHeaders>
    </httpProtocol>
    

    你也可以这样定义你的方法:

    [WebInvoke(Method = "*"
    

    这样你就可以满足各种要求了。

    【讨论】:

    • 添加*后没有运气
    • 嗨,你能帮我更多吗,因为我正在使用类库项目并在此提供宁静的服务我尝试使用 owin 启动类添加 startup.cs,但它没有触发。
    【解决方案2】:

    尝试添加标题 - 方法:

    <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, OPTIONS" />
    

    或安装this plugin

    【讨论】:

    • 我添加了这个标题,但没有成功
    • 嗨@ambussh,你能帮我更多吗,因为我正在使用类库项目并在此提供宁静的服务我尝试使用owin启动类添加startup.cs,但它没有触发。
    猜你喜欢
    • 2017-08-20
    • 2020-10-16
    • 2013-11-15
    • 2017-11-03
    • 2023-04-01
    • 2015-12-26
    • 2016-05-07
    相关资源
    最近更新 更多