简体   繁体   中英

Access Control Allow Origin issue with WCF service

  • I am new to WCF Restful Service and consuming the WCF project services in UI and getting the following error*

Error 1:- No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://localhost:2021 ' is therefore not allowed access.

Error 2:- Response for preflight has invalid HTTP status code 405.

I have done google and know that this is Cross Domain issue by Chrome. So I added the following in my 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>

and changed the method headers with folowing code.

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

Further I am using the SOAP service

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

And I am calling the method from 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) { });
};

Try add in header - methods:

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

or instal this plugin

add this to your web config file:

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

also you can define your method like this:

[WebInvoke(Method = "*"

this way you will cover all kinds of request.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM