Sha*_*tin 90 c# asp.net asp.net-web-api asp.net-identity
我们如何在安全的ApiController操作中获取当前用户,而不将userName或userId作为参数传递?
我们假设这是可用的,因为我们处于安全行动中.处于安全行动意味着用户已经过身份验证,并且请求具有她的承载令牌.鉴于WebApi已授权用户,可能存在一种内置方式来访问userId,而不必将其作为操作参数传递.
Dar*_*ler 138
在WebApi 2中,您可以在ApiController上RequestContext.Principal
的方法中使用
Pat*_*ick 36
您还可以使用该User
属性访问主体ApiController
.
所以以下两个语句基本相同:
string id;
id = User.Identity.GetUserId();
id = RequestContext.Principal.Identity.GetUserId();
Run Code Online (Sandbox Code Playgroud)
小智 14
提示位于Webapi2自动生成的帐户控制器中
将此属性与getter定义为
public string UserIdentity
{
get
{
var user = UserManager.FindByName(User.Identity.Name);
return user;//user.Email
}
}
Run Code Online (Sandbox Code Playgroud)
并且为了获得UserManager - 在WebApi2 -do中作为Romans(读作AccountController)做
public ApplicationUserManager UserManager
{
get { return HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>(); }
}
Run Code Online (Sandbox Code Playgroud)
这应该在IIS和自托管模式下兼容
小智 6
上面的建议对我都不起作用。以下做到了!
HttpContext.Current.Request.LogonUserIdentity.Name
Run Code Online (Sandbox Code Playgroud)
我想这里有各种各样的场景,这个场景对我有用。我的场景涉及一个在IIS下运行的AngularJS前端和一个Web API 2后端应用程序。我必须将两个应用程序都设置为仅在Windows身份验证下运行。
无需传递任何用户信息。浏览器和IIS交换登录的用户凭据,并且Web API可以按需访问用户凭据(我想是从IIS)。
小智 5
Karan Bhandari的答案很好,但在项目中添加的AccountController很可能是一个Mvc.Controller
.要将他的答案转换为在ApiController中使用的更改HttpContext.Current.GetOwinContext()
,Request.GetOwinContext()
并确保添加了以下2个using
语句:
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
Run Code Online (Sandbox Code Playgroud)
在 .Net Core 中用于User.Identity.Name
获取用户的 Name 声明。
归档时间: |
|
查看次数: |
119959 次 |
最近记录: |