2012-09-13 77 views
89

我使用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换MVC-两条腿-implementation.aspx”。这有助于我在客户端获取RequestToken。

但是,当我从客户端发布的数据,我得到了错误, “的XMLHttpRequest无法加载的http://请求头字段内容类型不被访问控制允许报头允许的。”

客户端码的样子,

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

+0

看看这个http://stackoverflow.com/questions/5027705/error-in-chrome-content-type-is-not-allowed-by-access-control-allow-headers并在你的网络配置中添加另一个规则 –

+0

你好吗?从您的浏览器和本地文件系统直接测试此js,例如file:// URL。并从哪个浏览器? –

回答

157

截至本岗位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> 
+0

感谢您的回复。它尝试了这一点,但我得到了错误,“XMLHttpRequest无法加载http:// localhost:54/api/Login.Access null不被Access-Control-Allow-Origin允许。 – Kishore

+0

@Kishore http://stackoverflow.com/questions/3595515/xmlhttprequest-error-origin-null-is-not-allowed-by-access-control-allow-origin –

+0

我仍然有这个没有运气,我有在这里详细发布:http://stackoverflow.com/questions/12437748/origin-null-is-not-allowed-by-access-control-allow-origin – Kishore

95

这是最可能的原因是跨域请求 ,但它可能不是。对我而言,我一直在调试一个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

+3

这个额外的头做了这项工作。 – Tarek

+3

为什么星号不包含所有内容 - - ; – user2483724

+3

@ user2483724这是因为星号允许任何Origin域,但它不指定允许哪些额外的标头。它只是说'你可以从其他地方的页面调用这个脚本' –

13

我知道这是一个古老的线程我上面的回答工作,不得不添加:

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

随着访问控制允许来源标题:

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

然后重新加载nginx的配置它运作得很好。信贷https://gist.github.com/algal/5480916

3

我用笨具有角4,我是遇到如下问题

我加了下面几行:

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

,解决...

+0

英语。 – gobrewers14

+0

Muito obrigado !! – CaptainHere

+2

您是否知道这个答案和我的2年后一样?你不是人们阅读吗? – DannyG

相关问题