联系 self-hosted WebApi 服务时出现 CORS Pre-flight 错误
CORS Pre-flight error when contacting self-hosted WebApi service
当 Web 门户联系 self-hosted WebAPI 服务时出现此错误,该服务位于 Web 门户服务器以外的其他服务器:
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'someportaldomain' is therefore not
allowed access.
self-hosted 服务总是在每个响应中 return "Access-Control-Allow-Origin" header,但是如果浏览器决定在调用 url, 用户在 js 控制台上得到这个错误。
我post这里的答案,因为我没有找到任何直接的答案,不得不从几个post中把它拉出来。
解决方案是将 Options 方法添加到自托管服务,如下所示:
[ServiceContract]
public interface IACT_HttpService
{
//[FaultContract(typeof(ValidationFault))]
[WebInvoke(Method = "OPTIONS", UriTemplate = "*")]
void GetOptions();
//My other methods
...
}
public class ACT_HttpService : IACT_HttpService
{
//Adjust this method to restrict the origin as needed
public void GetOptions()
{
log.Debug("Get options fired");
//These headers are handling the "pre-flight" OPTIONS call sent by the browser
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE,OPTIONS");
//Add here any special header you have
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-A}llow-Origin", "*");
WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
}
当 Web 门户联系 self-hosted WebAPI 服务时出现此错误,该服务位于 Web 门户服务器以外的其他服务器:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'someportaldomain' is therefore not allowed access.
self-hosted 服务总是在每个响应中 return "Access-Control-Allow-Origin" header,但是如果浏览器决定在调用 url, 用户在 js 控制台上得到这个错误。
我post这里的答案,因为我没有找到任何直接的答案,不得不从几个post中把它拉出来。
解决方案是将 Options 方法添加到自托管服务,如下所示:
[ServiceContract]
public interface IACT_HttpService
{
//[FaultContract(typeof(ValidationFault))]
[WebInvoke(Method = "OPTIONS", UriTemplate = "*")]
void GetOptions();
//My other methods
...
}
public class ACT_HttpService : IACT_HttpService
{
//Adjust this method to restrict the origin as needed
public void GetOptions()
{
log.Debug("Get options fired");
//These headers are handling the "pre-flight" OPTIONS call sent by the browser
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Methods", "POST,GET,PUT,DELETE,OPTIONS");
//Add here any special header you have
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-Allow-Headers", "X-Requested-With,Content-Type");
WebOperationContext.Current.OutgoingResponse.Headers.Add("Access-Control-A}llow-Origin", "*");
WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
}