我使用Visual Studio 2015创建一个Asp.net Core 1.0(WebApi)项目。模板为ASP.NET Core Web应用程序(.NET Core)\ WebApi(未选择身份验证)。
在ValuesController中,我想从正在调用该方法的客户端获取Windows身份。
using System.Security.Claims;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Http;
...
[Route("api/[controller]")]
public class ValuesController : Controller
{
[HttpGet]
[Route("GetIdentity")]
public string GetIdentity()
{
//method1
var userId = User.GetUserId();
//method2
var userId = User.FindFirst(ClaimTypes.NameIdentifier).Value;
return userId;
}
}
目前在method1
和中没有返回预期的结果method2
。有什么想法吗?
没有任何身份验证,任何Web框架都无法确定您的用户身份。
选择项目模板"ASP.NET Core Application (.NET Core)\WebApi
“,然后将身份验证从“ No Authentication
”更改为您认为合适的任何身份验证,例如“ Windows Authentication
”。
然后User
,如果使用[Authorize]
属性注释,则可以访问控制器的成员。
[Authorize]
[Route("api/[controller]")]
public class ValuesController : Controller
{
[HttpGet]
public string Get()
{
return User.Identity.Name;
}
}
如果要拥有单独的用户帐户,请选择MVC模板(而不是WebAPI)。然后,您可以注册各个帐户,并使用其凭据进行身份验证。
如果您是从没有身份验证的模板启动的,则可以launchSettings.json
在Properties
文件夹中的中启用Windows身份验证。
{
"iisSettings": {
"windowsAuthentication": true,
"anonymousAuthentication": false,
...
},
...
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句