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


102

我使用vS2012创建了一个mvc4 Web API项目。我使用以下教程来解决跨域资源共享,“ http://blogs.msdn.com/b/carlosfigueira/archive/2012/07/02/cors-support-in-asp-net-web-api- rc-version.aspx”。它正在成功运行,并且我将数据从客户端成功发布到服务器。

之后,为了在我的项目中实施Autherization,我使用了以下教程来实现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://。Access-Control-Allow-Headers不允许请求标头字段Content-Type。”

我的客户端代码看起来像

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


看看这个stackoverflow.com/questions/5027705/…,然后在您的网络配置中添加另一个规则
Mark Jones

嗨,您是直接从浏览器和本地文件系统(例如file:// URL)测试此js吗?从哪个浏览器?
马克·琼斯

Answers:


170

正如这篇文章所暗示的,chrome中错误:Access-Control-Allow-Headers不允许Content-Type,只需将其他标头添加到您的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>

谢谢您的回复。它尝试了此操作,但出现错误,“ XMLHttpRequest无法加载localhost:54 / api /Login。Access-Control-Allow-Origin不允许使用Origin null。”
Kishore 2012年


我仍然有这个没有运气,我已经张贴在这里详细:stackoverflow.com/questions/12437748/...
基肖尔

112

很有可能是由于跨域请求,但可能并非如此。对我来说,我一直在调试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在其他文件中使用过,否则将收到讨厌的错误消息。有关更多信息,请参阅文档


3
星号为何不覆盖所有内容--;
user2483724 2014年

3
@ user2483724,因为星号允许任何Origin域,但没有指定允许哪些其他头。它只是说,“您可以从在其他地方运行的页面调用此脚本”
Garet Claborn 2014年

18

我知道这是我在上述答案中使用的旧线程,必须添加:

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

问题已解决。


10

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

然后重新加载nginx配置,效果很好。信贷https://gist.github.com/algal/5480916

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.