Jquery 错误:访问控制允许标头不允许请求标头字段内容类型
我使用vS2012创建了一个MVC4WebAPI项目。我使用以下教程来解决跨源资源共享问题,”http://blogs.msdn.com/b/carlosfigueira/archive/2012/07/02/cors-support-in-asp-net-web-api-rc-version.aspx". 它工作成功,我成功地将数据从客户端发布到服务器 之后,为了在我的项目中实现身份验证,我使用了以下教程来实现OAuth2,“http://community.codesmithtools.com/CodeSmith_Community/b/tdupont/archive/2011/03/18/oauth-2-0-for-mvc-two-legged-implementation.aspx". 这有助于我在客户端获取RequestToken 但是当我从客户端发布数据时,我得到了错误, “XMLHttpRequest无法加载http://。访问控制允许标头不允许请求标头字段内容类型。” 我的客户端代码看起来像Jquery 错误:访问控制允许标头不允许请求标头字段内容类型,jquery,asp.net-mvc-4,asp.net-web-api,oauth-2.0,cors,Jquery,Asp.net Mvc 4,Asp.net Web Api,Oauth 2.0,Cors,我使用vS2012创建了一个MVC4WebAPI项目。我使用以下教程来解决跨源资源共享问题,”http://blogs.msdn.com/b/carlosfigueira/archive/2012/07/02/cors-support-in-asp-net-web-api-rc-version.aspx". 它工作成功,我成功地将数据从客户端发布到服务器 之后,为了在我的项目中实现身份验证,我使用了以下教程来实现OAuth2,“http://community.codesmithtools.co
function PostLogin() {
var Emp = {};
Emp.UserName = $("#txtUserName").val();
var pass = $("#txtPassword").val();
var hash = $.sha1(RequestToken + pass);
$('#txtPassword').val(hash);
Emp.Password= hash;
Emp.RequestToken=RequestToken;
var createurl = "http://localhost:54/api/Login";
$.ajax({
type: "POST",
url: createurl,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(Emp),
statusCode: {
200: function () {
$("#txtmsg").val("done");
toastr.success('Success.', '');
}
},
error:
function (res) {
toastr.error('Error.', 'sorry either your username of password was incorrect.');
}
});
};
[AllowAnonymous]
[HttpPost]
public LoginModelOAuth PostLogin([FromBody]LoginModelOAuth model)
{
var accessResponse = OAuthServiceBase.Instance.AccessToken(model.RequestToken, "User", model.Username, model.Password, model.RememberMe);
if (!accessResponse.Success)
{
OAuthServiceBase.Instance.UnauthorizeToken(model.RequestToken);
var requestResponse = OAuthServiceBase.Instance.RequestToken();
model.ErrorMessage = "Invalid Credentials";
return model;
}
else
{
// to do return accessResponse
return model;
}
}
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<section name="oauth" type="MillionNodes.Configuration.OAuthSection, MillionNodes, Version=1.0.0.0, Culture=neutral"/>
<sectionGroup name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection, DotNetOpenAuth.Core">
<section name="messaging" type="DotNetOpenAuth.Configuration.MessagingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" />
<section name="reporting" type="DotNetOpenAuth.Configuration.ReportingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" />
</sectionGroup>
</configSections>
<oauth defaultProvider="DemoProvider" defaultService="DemoService">
<providers>
<add name="DemoProvider" type="MillionNodes.OAuth.DemoProvider, MillionNodes" />
</providers>
<services>
<add name="DemoService" type="MillionNodes.OAuth.DemoService, MillionNodes" />
</services>
</oauth>
<system.web>
<httpModules>
<add name="OAuthAuthentication" type="MillionNodes.Module.OAuthAuthenticationModule, MillionNodes, Version=1.0.0.0, Culture=neutral"/>
</httpModules>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules>
<add name="OAuthAuthentication" type="MillionNodes.Module.OAuthAuthenticationModule, MillionNodes, Version=1.0.0.0, Culture=neutral" preCondition="" />
</modules>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
<dotNetOpenAuth>
<messaging>
<untrustedWebRequest>
<whitelistHosts>
<!-- Uncomment to enable communication with localhost (should generally not activate in production!) -->
<!--<add name="localhost" />-->
</whitelistHosts>
</untrustedWebRequest>
</messaging>
<!-- Allow DotNetOpenAuth to publish usage statistics to library authors to improve the library. -->
<reporting enabled="true" />
我的api控制器看起来像
function PostLogin() {
var Emp = {};
Emp.UserName = $("#txtUserName").val();
var pass = $("#txtPassword").val();
var hash = $.sha1(RequestToken + pass);
$('#txtPassword').val(hash);
Emp.Password= hash;
Emp.RequestToken=RequestToken;
var createurl = "http://localhost:54/api/Login";
$.ajax({
type: "POST",
url: createurl,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(Emp),
statusCode: {
200: function () {
$("#txtmsg").val("done");
toastr.success('Success.', '');
}
},
error:
function (res) {
toastr.error('Error.', 'sorry either your username of password was incorrect.');
}
});
};
[AllowAnonymous]
[HttpPost]
public LoginModelOAuth PostLogin([FromBody]LoginModelOAuth model)
{
var accessResponse = OAuthServiceBase.Instance.AccessToken(model.RequestToken, "User", model.Username, model.Password, model.RememberMe);
if (!accessResponse.Success)
{
OAuthServiceBase.Instance.UnauthorizeToken(model.RequestToken);
var requestResponse = OAuthServiceBase.Instance.RequestToken();
model.ErrorMessage = "Invalid Credentials";
return model;
}
else
{
// to do return accessResponse
return model;
}
}
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<section name="oauth" type="MillionNodes.Configuration.OAuthSection, MillionNodes, Version=1.0.0.0, Culture=neutral"/>
<sectionGroup name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection, DotNetOpenAuth.Core">
<section name="messaging" type="DotNetOpenAuth.Configuration.MessagingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" />
<section name="reporting" type="DotNetOpenAuth.Configuration.ReportingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" />
</sectionGroup>
</configSections>
<oauth defaultProvider="DemoProvider" defaultService="DemoService">
<providers>
<add name="DemoProvider" type="MillionNodes.OAuth.DemoProvider, MillionNodes" />
</providers>
<services>
<add name="DemoService" type="MillionNodes.OAuth.DemoService, MillionNodes" />
</services>
</oauth>
<system.web>
<httpModules>
<add name="OAuthAuthentication" type="MillionNodes.Module.OAuthAuthenticationModule, MillionNodes, Version=1.0.0.0, Culture=neutral"/>
</httpModules>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules>
<add name="OAuthAuthentication" type="MillionNodes.Module.OAuthAuthenticationModule, MillionNodes, Version=1.0.0.0, Culture=neutral" preCondition="" />
</modules>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
<dotNetOpenAuth>
<messaging>
<untrustedWebRequest>
<whitelistHosts>
<!-- Uncomment to enable communication with localhost (should generally not activate in production!) -->
<!--<add name="localhost" />-->
</whitelistHosts>
</untrustedWebRequest>
</messaging>
<!-- Allow DotNetOpenAuth to publish usage statistics to library authors to improve the library. -->
<reporting enabled="true" />
我的网络配置文件看起来像
function PostLogin() {
var Emp = {};
Emp.UserName = $("#txtUserName").val();
var pass = $("#txtPassword").val();
var hash = $.sha1(RequestToken + pass);
$('#txtPassword').val(hash);
Emp.Password= hash;
Emp.RequestToken=RequestToken;
var createurl = "http://localhost:54/api/Login";
$.ajax({
type: "POST",
url: createurl,
contentType: "application/json; charset=utf-8",
data: JSON.stringify(Emp),
statusCode: {
200: function () {
$("#txtmsg").val("done");
toastr.success('Success.', '');
}
},
error:
function (res) {
toastr.error('Error.', 'sorry either your username of password was incorrect.');
}
});
};
[AllowAnonymous]
[HttpPost]
public LoginModelOAuth PostLogin([FromBody]LoginModelOAuth model)
{
var accessResponse = OAuthServiceBase.Instance.AccessToken(model.RequestToken, "User", model.Username, model.Password, model.RememberMe);
if (!accessResponse.Success)
{
OAuthServiceBase.Instance.UnauthorizeToken(model.RequestToken);
var requestResponse = OAuthServiceBase.Instance.RequestToken();
model.ErrorMessage = "Invalid Credentials";
return model;
}
else
{
// to do return accessResponse
return model;
}
}
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=4.4.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<section name="oauth" type="MillionNodes.Configuration.OAuthSection, MillionNodes, Version=1.0.0.0, Culture=neutral"/>
<sectionGroup name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection, DotNetOpenAuth.Core">
<section name="messaging" type="DotNetOpenAuth.Configuration.MessagingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" />
<section name="reporting" type="DotNetOpenAuth.Configuration.ReportingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" />
</sectionGroup>
</configSections>
<oauth defaultProvider="DemoProvider" defaultService="DemoService">
<providers>
<add name="DemoProvider" type="MillionNodes.OAuth.DemoProvider, MillionNodes" />
</providers>
<services>
<add name="DemoService" type="MillionNodes.OAuth.DemoService, MillionNodes" />
</services>
</oauth>
<system.web>
<httpModules>
<add name="OAuthAuthentication" type="MillionNodes.Module.OAuthAuthenticationModule, MillionNodes, Version=1.0.0.0, Culture=neutral"/>
</httpModules>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="Forms">
<forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules>
<add name="OAuthAuthentication" type="MillionNodes.Module.OAuthAuthenticationModule, MillionNodes, Version=1.0.0.0, Culture=neutral" preCondition="" />
</modules>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
<dotNetOpenAuth>
<messaging>
<untrustedWebRequest>
<whitelistHosts>
<!-- Uncomment to enable communication with localhost (should generally not activate in production!) -->
<!--<add name="localhost" />-->
</whitelistHosts>
</untrustedWebRequest>
</messaging>
<!-- Allow DotNetOpenAuth to publish usage statistics to library authors to improve the library. -->
<reporting enabled="true" />
正如这篇文章所暗示的,只需在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>
正如这篇文章所暗示的,只需在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>
这很可能是由于跨源请求造成的,但可能不是。对我来说,我一直在调试一个API,并将
访问控制允许源代码设置为*
,但最近的Chrome版本似乎需要一个额外的标题。如果您使用的是PHP,请尝试在文件前添加以下内容:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
确保您尚未在另一个文件中使用头文件
,否则会出现严重错误。有关更多信息,请参阅。这很可能是由于跨源请求造成的,但可能不是。对我来说,我一直在调试一个API,并将访问控制允许源代码设置为*
,但最近的Chrome版本似乎需要一个额外的标题。如果您使用的是PHP,请尝试在文件前添加以下内容:
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
确保您尚未在另一个文件中使用头文件
,否则会出现严重错误。有关更多信息,请参阅。我知道这是我使用上述答案时使用的一个旧线程,必须添加:
header('Access-Control-Allow-Methods: GET, POST, PUT');
所以我的标题看起来像:
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header('Access-Control-Allow-Methods: GET, POST, PUT');
问题已经解决。我知道这是一个旧线程,我使用了上面的答案,必须添加:
header('Access-Control-Allow-Methods: GET, POST, PUT');
所以我的标题看起来像:
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header('Access-Control-Allow-Methods: GET, POST, PUT');
问题已经解决。对于Nginx,唯一对我有效的方法是添加以下标题:
add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since';
与访问控制允许原点标题一起:
add_header 'Access-Control-Allow-Origin' '*';
然后重新加载nginx配置,效果非常好。信贷。对于Nginx,唯一对我有效的方法就是添加以下标题:
add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type,Accept,Origin,User-Agent,DNT,Cache-Control,X-Mx-ReqToken,Keep-Alive,X-Requested-With,If-Modified-Since';
与访问控制允许原点标题一起:
add_header 'Access-Control-Allow-Origin' '*';
然后重新加载nginx配置,效果非常好。信用。有同样的问题,但与我的案例中的其他答案不同,我使用ASP.NET开发WebAPI服务器
我已经得到了兵团的许可,它可以满足GET请求。为了使POST请求生效,我需要将“AllowAnyHeader()”和“AllowAnyMethod()”选项添加到公司选项列表中
下面是Start类中相关函数的基本部分,如下所示:
配置服务方法:
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder
.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod()
//.AllowCredentials()
;
});
});
app.UseCors(MyAllowSpecificOrigins);
配置方法:
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder
.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod()
//.AllowCredentials()
;
});
});
app.UseCors(MyAllowSpecificOrigins);
从以下位置找到此文件:
也有同样的问题,但与我的案例中的其他答案不同,我使用ASP.NET开发WebAPI服务器
我已经得到了兵团的许可,它可以满足GET请求。为了使POST请求生效,我需要将“AllowAnyHeader()”和“AllowAnyMethod()”选项添加到公司选项列表中
下面是Start类中相关函数的基本部分,如下所示:
配置服务方法:
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder
.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod()
//.AllowCredentials()
;
});
});
app.UseCors(MyAllowSpecificOrigins);
配置方法:
services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder
.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod()
//.AllowCredentials()
;
});
});
app.UseCors(MyAllowSpecificOrigins);
从以下位置找到此文件:
看看这一点,并在您的web配置中添加另一条规则。您是否直接从浏览器和本地文件系统(例如file://URL)测试此js。??从哪个浏览器?看一看,并在您的web配置中添加另一条规则。您是否直接从浏览器和本地文件系统(如file://URL.)测试此js。??来自哪个浏览器?谢谢回复。它尝试了这一点,但我得到了错误,“XMLHttpRequest无法加载。访问控制允许源代码不允许源代码为null。”@Kishore我对此仍然没有把握,我已经在这里发布了详细信息:谢谢回复。它尝试了这一点,但我得到了错误,“XMLHttpRequest无法加载。访问控制允许源代码不允许源代码为null。”@Kishore我对此仍然没有运气,我在这里发布了详细信息:为什么星号没有涵盖所有内容--@user2483724这是因为星号允许任何源域,但它没有指定允许哪些附加头。它只是说,‘你可以从其他地方运行的页面调用这个脚本’,为什么星号不能覆盖所有内容@user2483724这是因为星号允许任何源域,但它没有指定允许哪些附加头。它只是说,‘您可以从其他地方运行的页面调用此脚本’