1

前段時間,我使用asp.net Web-api beta構建了API。我在某處讀到,當在IIS中託管時,web-api繼承了其運行的Web應用程序中的Identity。我的api也在一個網站上運行。使用測試版的二進制文件,當我登錄到網站,然後移動到http://localhost:4343/webui/api/values它會返回給我登錄用戶的正確值。這裏是值控制器的Get方法。使用新的ASP.NET Web API的主體

public IQueryable<string> Get() 
     { 
      var pr = Request.GetUserPrincipal(); 
      var username = Request.GetUserPrincipal().Identity.Name; //Null reference exception after installing vs 2012 here. Identity is null even though I am logged in 
      var values = GetUserValues(username); 
      return values.AsQueryable(); 
     } 

它曾經與web-api的beta版本正常工作,但與最終版本的vs2012它拋出空引用異常。我已將該網站轉換爲使用.net 4.5。任何想法發生了什麼?

回答

1

HttpRequestMessage沒有任何方法或擴展名,如GetUserPrincipal。我不確定是否有beta版。正如我從你的問題中瞭解到的,你的應用程序仍在運行測試版,這是一個完整的IMO災難。

當您安裝VS 2012時,Web API程序集已在您的計算機上進行了GAC。所以,你很有可能在那裏發生衝突。

在另一方面,你可以通過下面的命令得到了認同:

var principal = Thread.CurrentPrincipal; 
+0

讓我吃驚的是VS 2012在nuget中增加了'System.Net.Http.Formatting'和一些其他程序集。我也認爲他們會被GACed,但可能他們不是。 'Thread.CurrentPrincipal'是我採用的路線,但我認爲訪問'User'屬性是更清晰的方法。 –

5

的ApiController現在有一個名爲「用戶」,這是IPrincipal的財產。

var pr = User.Identity.Name; 

在內部,User屬性調用tugberk提到的Thread.CurrentPrincipal。

+0

如何在'DelegatingHandler'中檢查身份驗證後設置User屬性。 –

+0

在測試版中,我用'Request.Properties [HttpPropertyKeys.UserPrincipal] = new Generic Pricipal(..);'來編寫。看起來委託人是從Http屬性中刪除的,不是? –

+0

只是好奇,爲什麼你要設置用戶屬性?是否需要進行單元測試? – omerthe1st