【发布时间】: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) { });
};
【问题讨论】: