2016-08-16 19 views
0

有人可以向我解釋,如果可以在AngularJS Promise中從Web API響應中獲取標題嗎?爲什麼AngularJS Promise無法從WEB API響應中檢索標題?

我提出以下電話:

return $http({ 
     url: "http://localhost:19260/api/Authentication/Login/{credentials}", 
     method: "POST", 
     data: JSON.stringify(input), 
     dataType: "json" 
    }).then(function (response) { 
     if (response.status === 200) { 
      var jwt= response.headers('A‌​uthorization'); //Always null!!!! 
      auth = true; 
     } 
     else { 
      auth = false; 
     } 
    }, function (response) { 
     auth = false; 
    }); 

每次我嘗試通過「response.headers(......)」讀我的頭值爲null。爲什麼是這樣?當我看着小提琴手的迴應時,我可以看到標題及其價值。爲什麼AngularJS無法看到它?

這是CORS的問題嗎?客戶端/服務器都在本地主機上運行,​​但具有不同的端口。如果是這樣,我的CORS實施有什麼問題? (C#)

[EnableCors(origins: "*", headers: "*", methods: "*")] 
public class AuthenticationController : ApiController 
{ 
    [Route("api/Authentication/Login/{credentials}")] 
    [HttpPost] 
    public HttpResponseMessage Login([FromBody]CredentialContainer credentials) 
    { 
      var response = new HttpResponseMessage(); 
      var jwt = GetJwtToken(credentials);    
      response.Headers.Add("Authorization", jwt); 
      response.StatusCode = HttpStatusCode.OK; 
      return response; 
    } 
+0

可能想看看這個問題:http://stackoverflow.com/q/27623389/215552。它不是重複的,但是在Web API中使用CORS提供了很好的建議。 –

+0

global.asax中的enableCors()也是? – naveen

+0

@naveen你的意思是在WebApiConfig.cs中? – Dave

回答

0

你可能不會在你的Web API服務和Web服務器的配置考慮兩點:

第一: 由於非默認的標題值沒有顯示到客戶端(即授權和任何其他自定義標題),直到您通過在web服務器(IIS Web.config)中設置一些配置來公開它們。您可以公開他們Web.config喜歡這裏:

<system.webServer> 
    <httpProtocol> 
    <customHeaders> 
     <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept, Authorization" /> 
     <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS,PUT,DELETE" /> 
     <add name="Access-Control-Allow-Origin" value="*" /> 
    </customHeaders> 
    </httpProtocol> 
</system.webServer> 

如果你是加納設置這些配置對於所有的API,這是最好的辦法,也沒有必要在每個方法的頂部添加enable-cors屬性。同樣在web.config中設置這些配置要容易得多,而且工作起來更加簡單(就像我的經驗一樣)。

第二個: 您沒有正確地在ajax請求中獲取頭中的授權值。 請嘗試下面的代碼:

return $http({ 
     url: "http://localhost:19260/api/Authentication/Login/{credentials}", 
     method: "POST", 
     data: JSON.stringify(input), 
     dataType: "json" 
    }).success(function (response, status, headers, config) { 
     if (response.status === 200) { 
      //Try this one 
      var jwt= headers('A‌​uthorization'); 
      auth = true; 
     } 
     else { 
      auth = false; 
     } 
    }).error(function (response, status, headers, config) { 
     auth = false; 
    }); 

希望這可以幫助你兄弟。祝你好運。

+0

感謝您的迴應,但不幸的是,這不起作用。我的響應對象現在是一個空字符串「」,並且標題對象仍然沒有我的值。 – Dave

+0

不客氣兄弟,沒問題。您可以在谷歌瀏覽器開發人員選項(Ctrl + Shift + I)中查看響應,然後轉到網絡選項卡。現在觸發您希望的請求到服務器,在響應成功接收後,您可以獲得有關請求和響應的所有信息(包括頭文件等)。如果您的響應內容再次爲空,則必須再次調試服務器端代碼,但如果不嘗試重構客戶端請求代碼片段。再次通知我,如果你不會得到你的結果。 GL –

相關問題