【发布时间】:2016-11-03 08:32:01
【问题描述】:
我是 angularjs 的新手,并尝试使用 angularjs 客户端使用 wcf restful 服务。最初我尝试了 http.get(url) 并得到了我通过将以下代码放入我想要的 wcf 服务方法中解决的 CORS 问题打电话。
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", ""); WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods", "POST,GET,OPTIONS"); WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Accept");*
现在,当我以与 get 相同的方式发出后调用 (http.post) 时,我得到了回复,但没有出现 CORS 问题。
但是当我尝试在发帖时传递 JSON 对象时,我再次开始遇到 CORS 问题。
我的帖子角码是:
var requestData = {
RequestUserName: "Abc1",
RequestPass: "123"
};
var req = {
method: 'POST',
url: 'url',
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
data: requestData
};
$http(req).success(function(){console.log("Success");
$scope.userDetails = response.UserNameAuthenticationResult;}).error(function(){console.log("Error");});
我的 WCF 操作合约如下:
[WebInvoke(Method="POST",UriTemplate="/Authenticate"
,RequestFormat=WebMessageFormat.Json
,ResponseFormat=WebMessageFormat.Json
,BodyStyle = WebMessageBodyStyle.Wrapped)]
string UserNameAuthentication(Request request);
方法实现如下:
public string UserNameAuthentication(Request request)
{
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Origin", "*");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods", "POST,GET,OPTIONS");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "Content-Type, Accept");
return "true";
}
我得到的错误如下:
**OPTIONS URL (匿名函数) @ angular.js:11442sendReq @ angular.js:11235serverRequest @ angular.js:10945processQueue @ angular.js:15552(匿名函数)@ angular.js:15568$eval @ angular.js:16820$digest @ angular.js:16636$apply @ angular.js:16928(匿名函数)@ angular.js:24551defaultHandlerWrapper @ angular.js:3398eventHandler @ angular.js:3386 localhost/:1 XMLHttpRequest 无法加载 http://localhost:8733/TestService/Login/Authenticate。响应 预检请求未通过访问控制检查:否 请求中存在“Access-Control-Allow-Origin”标头 资源。因此不允许使用原点“http://localhost:14703” 使用权。响应的 HTTP 状态代码为 405。
【问题讨论】:
-
我认为与 angularjs 无关。您需要在 wcf 应用程序中配置 CORS。 check this out.
-
这没有帮助,我已经尝试将这段代码放在 wcf 服务的调用方法中,但仍然是同样的错误。此外,由于我已将 wcf 服务构建为类库,因此我没有添加 global.asax 文件的选项,但我们确实在 wcf 应用程序中获得了它,因此我在调用方法中添加了 Headers 代码。
-
Arjun- 我添加了插件,但没有收到上述错误,但我收到了一个新错误,上面写着 net::ERR_CONNECTION_REFUSED。
-
考虑到我将rest服务构建为WCF服务库而不是WCF服务应用程序,如果有人可以提供示例解决方案,那将非常有帮助。
标签: .net angularjs rest wcf cors