2017-08-09 14 views
6

我的Web Core API中的这段代码证实我是一个经过身份验证的用户,但我没有得到我的用户名,而是得到应用程序池的名称。 我该如何解决这个问题?为什么我没有在Windows认证的Web Core API中获取我的用户名?

var testa = User.Identity.GetType(); 
NLogger.Info($"testa = {testa}"); 
var testd = User.Identity.IsAuthenticated; 
NLogger.Info($"testd = {testd}"); 
var loggedInUser = User.Identity.Name; 
NLogger.Info($"loggedInUser = {loggedInUser}"); 

在我的日志文件中,我得到了;

testa = System.Security.Principal.WindowsIdentity 
testd = True 
loggedInUser = IIS APPPOOL\SIR.WEBUI 

我使用[Authorize]标签作为控制器,匿名认证被禁用。

那么我打电话给Postman的方法,它工作正常,LoggedInUser是正确的。但是当我从我的代码中调用时,我得到了上面显示的不正确的loggedInUser。 我用来从我的客户端应用程序调用web api的代码是;

public static async Task<IEnumerable<ContractDto>> GetAllForUser() 
{ 
    using (var client = new HttpClient(new HttpClientHandler { UseDefaultCredentials = true })) 
    { 
     client.BaseAddress = new Uri(AppSettings.ServerPathApi); 
     var path = GetPath("getallforuser"); 
     var response = await client.GetAsync(path); 
     response.EnsureSuccessStatusCode(); 
     var stringResult = await response.Content.ReadAsStringAsync(); 
     return JsonConvert.DeserializeObject<IEnumerable<ContractDto>>(stringResult); 
    } 
} 

在IIS中,我将应用程序池类型设置为所有不同的选项;应用程序,网络服务,本地服务,本地系统和每次测试应用程序。我究竟在想什么?

+0

一个接受的答案类似的问题在这里https://stackoverflow.com/a/12675503/5233410 – Nkosi

+0

我不知道如果这是问题,但我建议你尝试在IIS – Shahbaz

+0

@Nkosi中将“加载用户配置文件”设置为true(如果还没有的话),尝试过,但不起作用。我正在使用Web Core API,我认为模拟的工作方式不同。也许我应该使用模拟?但是,当我使用AJAX时,我不需要这么做,那么为什么C#会有所不同呢? – arame3333

回答

0

试试这个

if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated) 
{ 
    string username = System.Web.HttpContext.Current.User.Identity.Name; 
} 

,或者你可以尝试

var user = (System.Security.Principal.WindowsIdentity)HttpContext.Current.User.Identity; 
var userName = user.Impersonate(); 
+0

做了一些研究后,我发现来自AJAX的调用将从浏览器中获取我的身份,但通过IIS它将取代应用程序池。 IIS的解决方案是使用模拟,我现在正在研究。 – arame3333

+0

@ arame3333如果要添加模拟,请使用第二个代码,但添加此部分var userName = user.Impersonate()。我已编辑的答案包括它 –

+0

@ arame3333你可以检查这个链接有一个类似的问题在这里[获取证书的请求](https://stackoverflow.com/questions/12212116/how-to-get-httpclient-to -pass-credentials -with-the-request/12675503#12675503) –

相关问题