错误:请求标头字段Content-Type不被Access-Control-Allow-Headers所允许

我使用vS2012创build了一个mvc4 web api项目。 我使用以下教程来解决跨源资源共享,“http://blogs.msdn.com/b/carlosfigueira/archive/2012/07/02/cors-support-in-asp-net-web-api- RC-version.aspx”。 它正在成功工作,我成功地从客户端发送数据到服务器。

之后,在我的项目中实现了validation,我用下面的教程来实现OAuth2,“http://community.codesmithtools.com/CodeSmith_Community/b/tdupont/archive/2011/03/18/oauth-2-0-for -mvc两足-implementation.aspx”。 这有助于我在客户端获取RequestToken。

但是,当我从客户端发布数据,我得到了错误, “XMLHttpRequest无法加载http://。请求标头字段内容types是不允许的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; } } 

我的webconfig文件看起来像,

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

正如这篇文章所暗示的那样:Chrome中的错误:Content-Type不被Access-Control-Allow-Headers所允许,只是像你这样将附加的头文件添加到你的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> 

这很可能是由于一个交叉来源的请求 ,但它可能不是。 对于我来说,我一直在debugging一个API,并将Access-Control-Allow-Origin* ,但似乎最近的Chrome版本需要额外的头文件。 如果您正在使用PHP,请尝试将以下内容添加到您的文件中:

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

确保你还没有在另一个文件中使用header ,否则你会得到一个讨厌的错误。 有关更多信息,请参阅文档 。

我知道这是一个古老的线程,我与上面的答案,不得不补充:

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

与Access-Control-Allow-Origin标题一起:

 add_header 'Access-Control-Allow-Origin' '*'; 

然后重新加载nginxconfiguration,它工作得很好。 信用https://gist.github.com/algal/5480916

我用angular4使用codeigniter,我遇到了这个问题…

我加了下面几行:

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

解决了…