我很有棱角。现在我对WCF的角度POST有一些问题。
这是WCF合同:
[OperationContract]
[WebInvoke(Method = "POST",
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
UriTemplate = "/InsertJSONSTRING/")]
void InsertJSONSTRING(DyeMaster value);
这是角度控制器
app.controller('UploadCOJSON', function ($scope, $http) {
$scope.SendData = function () {
function DYE() {
this.DESCRIPTION;
this.COLOR_CODE;
}
$scope.dye = new DYE();
$scope.dye.DESCRIPTION = $scope.DESCRIPTION;
$scope.dye.COLOR_CODE = $scope.COLOR_CODE;
var dataR = JSON.stringify($scope.dye);
$http({
url: "http://localhost:63599/ServiceMobileListener.svc/InsertJSONSTRING",
method: "POST",
data: dataR,
dataType: "json",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
});
}
});
这是错误:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:63599/ServiceMobileListener.svc/InsertJSONSTRING. This can be fixed by moving the resource to the same domain or enabling CORS.
不知何故,当我排除参数(数据)时,它没有任何错误。
$http({
url: "http://localhost:63599/ServiceMobileListener.svc/InsertJSONSTRING",
method: "POST",
dataType: "json",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
});
注意:已按照此处所述http://enable-cors.org/server_wcf.html启用CORS
感谢您的帮助。
答案 0 :(得分:1)
您必须在inspect元素中查看您的网络选项卡,它必须在POST请求之前发出OPTIONS请求。您需要使用CORS标头回复服务器端的选项请求。
当您不发送数据时,浏览器不得发出OPTIONS请求,因此它就是在这种情况下工作。
对于回复中的选项请求
添加这些标题
"Access-Control-Allow-Origin", "http://my.requestmaking-site.com"
"Access-Control-Allow-Methods", "POST, GET, OPTIONS"
可选择如果您允许身份验证
"Access-Control-Allow-Headers", "Content-Type, Authorization"
"Access-Control-Allow-Credentials", "true"
无需在回复正文中发送任何内容
答案 1 :(得分:0)
只需在web.config文件中添加这些参数..
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*"/>
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept"/>
</customHeaders>
</httpProtocol>