2012-09-13 84 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

相關問題