【问题标题】:Error :Request header field Content-Type is not allowed by Access-Control-Allow-Headers错误:Access-Control-Allow-Headers 不允许请求标头字段 Content-Type
【发布时间】:2012-09-06 17:42:48
【问题描述】:

我使用 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 无法加载 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/… 并在你的网络配置中添加另一个规则
  • 您好,您是直接从浏览器和本地文件系统测试这个 js,例如文件:// 网址.??来自哪个浏览器?

标签: jquery asp.net-mvc-4 asp.net-web-api oauth-2.0 cors


【解决方案1】:

正如这篇文章 Error in chrome: Content-Type is not allowed by 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>

【讨论】:

【解决方案2】:

这很可能是由于跨域请求,但也可能不是。对我来说,我一直在调试 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,否则您将收到一个严重错误。请参阅the docs 了解更多信息。

【讨论】:

  • 为什么星号不能涵盖所有内容 - -;
  • @user2483724 这是因为星号允许任何 Origin 域,但它没有指定允许哪些附加标头。它只是说,'你可以从其他地方运行的页面调用这个脚本'
【解决方案3】:

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

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

问题就解决了。

【讨论】:

    【解决方案4】:

    对于 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

    【讨论】:

      【解决方案5】:

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

      我已经允许 Corps,它适用于 GET 请求。为了使 POST 请求正常工作,我需要将“AllowAnyHeader()”和“AllowAnyMethod()”选项添加到 Corp 选项列表中。

      Start 类中相关函数的基本部分如下所示:

      ConfigureServices 方法:

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

      配置方法:

              app.UseCors(MyAllowSpecificOrigins);
      

      发现于:

      【讨论】:

      • 虽然 CORS 默认情况下不允许 Content-Type 标头吗?
      猜你喜欢
      • 2013-07-05
      • 2011-06-29
      • 2014-06-16
      • 2018-08-26
      • 1970-01-01
      • 1970-01-01
      • 2019-03-17
      相关资源
      最近更新 更多