错误: 访问控制-允许-标头不允许请求标头字段 Content-Type

我使用 vS2012创建了一个 mvc4 web api 项目。我用下面的教程来解决这个跨来源资源共享,“ 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 cannot load http://. Request header field Content-Type is not allowed by Access-Control-Allow-Headers."

我的 客户端代码看起来像,

 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.');
}
});
};

我的 API 控制器看起来像,

    [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;
}


}

My Webconfig file look like,

 <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" />

217644 次浏览

正如本文所暗示的那样,Chrome 错误: 访问控制允许标题不允许内容类型只需将额外的头文件添加到 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>

It is most likely due to a 跨来源请求, but it may not be. For me, I had been debugging an API and had set the Access-Control-Allow-Origin to *, but it appears that recent versions of Chrome are requiring an extra header. Try prepending the following to your file if you are using PHP:

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

Make sure that you haven't already used header in another file, or you will get a nasty error. See 那些文件 for more.

I know it's an old thread I worked with above answer and had to add:

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');

问题解决了。

For Nginx, the only thing that worked for me was adding this header:

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' '*';

Then reloaded the nginx config and it worked great. Credit https://gist.github.com/algal/5480916.

遇到了同样的问题,但是我使用 ASP.NET 来开发 WebAPI 服务器与其他答案不同。

我已经得到了公司的许可,它可以满足 GET 请求。为了使 POST 请求工作,我需要在 Corp 选项列表中添加“ AllowAnyHeader ()”和“ AllowAnyMethod ()”选项。

以下是 Start 类中相关函数的基本部分:

ConfigureServices 方法:

    services.AddCors(options =>
{
options.AddPolicy(name: MyAllowSpecificOrigins,
builder =>
{
builder
.WithOrigins("http://localhost:4200")
.AllowAnyHeader()
.AllowAnyMethod()
//.AllowCredentials()
;
});
});

配置方法:

        app.UseCors(MyAllowSpecificOrigins);

发现了这个: