我在前端有Ajax调用,并且我通过ajax调用来调用WCF服务,但是ajax调用具有一些添加标头,这就是为什么首个预检OPTIONS请求被提出并且由于“ url”而被拒绝的原因已被cors策略阻止。 / p>
我已经在我的web.config文件中添加了“以下代码”,但是仍然可以正常工作。
<system.webServer>
<security>
<requestFiltering>
<verbs>
<add verb="OPTIONS" allowed="true" />
<add verb="POST" allowed="true" />
<add verb="GET" allowed="true" />
<add verb="DELETE" allowed="false" />
</verbs>
</requestFiltering>
</security>
<httpProtocol>
<customHeaders>
<remove name="X-Powered-By" />
<add name="Access-Control-Allow-Credentials" value="true" />
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Methods" value="GET,POST,DELETE,OPTIONS" />
<add name="Access-Control-Allow-Headers" value="accept, cache-control, content-type, authorization, context" />
</customHeaders>
</httpProtocol>
</system.webServer>
$.ajax({
async: true,
type: "POST",
headers: {
'Authorization': 'Basic ' + btoa(BasicAuth),
'Context': 'Context' + btoa(ContextHeader)
},
contentType: "application/json; charset=utf-8",
data: '{"Id": "' + Id + '" }',
url: URL + "/MethodName",
success: function (result) {
response = result;
if (response == true)
Xrm.Page.data.refresh(true);
$('#msgDiv').fadeOut('slow');
},
error: function (status) {
console.log(status.status);
$('#msgDiv').fadeOut('slow');
Configurations.OnFailure(status);
}
});
我在javascript上写过的代码。
在HTTP上调用正常,但是在HTTPS上调用无效。
我在控制台上收到如下错误
enter code here
选项https://abc/xyz 400(错误请求)
从原点“ https://abc/xyz”到“ https://Localhost的XMLHttpRequest的访问已被CORS策略阻止:对预检请求的响应未通过访问控制检查:没有HTTP正常状态
答案 0 :(得分:0)
这是“我的CORS”解决方案,希望它对您有用。将全局应用程序类添加到我的wcf服务应用程序中。
Global.asax
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
{
HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With,Accept");
HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
HttpContext.Current.Response.End();
}
}
服务器上的web.config
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding name="mybinding">
<security mode="Transport">
<transport clientCredentialType="Basic" proxyCredentialType="Basic"></transport>
</security>
</binding>
</webHttpBinding>
</bindings>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true"/>
<dataContractSerializer maxItemsInObjectGraph="2147483647"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior>
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true">
</serviceHostingEnvironment>
<protocolMapping>
<add scheme="https" binding="webHttpBinding" bindingConfiguration="mybinding"/>
<add scheme="http" binding="webHttpBinding" />
</protocolMapping>
</system.serviceModel>
然后在客户端(我们在其中运行JS)中安装服务器服务证书。
JS。
<script>
function make_base_auth(user, password) {
var tok = user + ':' + password;
var hash = window.btoa(tok); //javascript built-in function
return "Basic " + hash;
}
$(function () {
$.ajax({
type: "GET",
url: "https://vabqia130vm:12001/service1.svc/getdata?value=34",
contentType: "application/json;charset=utf-8",
beforeSend: function (req) {
req.setRequestHeader("Authorization", make_base_auth("administrator",
"abcde12345!"));
},
success: function (d) {
console.log(d);
},
});
})
</script>
答案 1 :(得分:-1)
我在服务端创建了dispatchmessageInspector,以在调用实际服务之前检查身份验证是否正确。
以下我编写的用于在调度员检查器上处理身份验证的代码。
public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
var logFileName = SetLogInfo("JavaScriptBasicAuth");
try
{
if (!HttpContext.Current.Request.HttpMethod.Equals("OPTIONS"))
{
var basicAuth = HttpContext.Current.Request.Headers["Authorization"];
if (basicAuth != null)
{
string[] separator = basicAuth.Split(' ');
BasicAuthenticationBehaviorAttribute basicauth = new BasicAuthenticationBehaviorAttribute();
if (!basicauth.ValidateBasicAuth(separator[1]))
{
throw new WebFaultException(HttpStatusCode.Unauthorized);
}
}
else
{
FileLogger.LogError("401 (Unauthorized) Error - " + "You are not authorized to perform this operation. Please contact administrator.", LOG_SUB_DIRECTORY, logFileName);
throw new WebFaultException(HttpStatusCode.Unauthorized);
}
}
}
但是在Dispatcher检查器代码之前呼叫失败。