更新
请参阅this answer 关于使用声明...
在控制器中,您可以像这样获取当前用户:
using Microsoft.AspNet.Identity.Owin;
public class MyController : Controller
{
// this code will return 0 if user is not authenticated
protected long GetUserId()
{
// note: I have changed the default UserId type from Guid to long
return User.Identity.GetUserId<long>();
/*
* use this if you are using Guid UserIds (which is the default)
* return User.Identity.GetUserId();
*/
}
如果您想知道如何更改UserId 的类型,请参阅this。
如果你可以访问HttpContext,你可以这样获取用户:
// note that I have changed UserId from Guid to long
HttpContext.Current.User.Identity.GetUserId<long>()
如果你想获得 ApplicationUser 使用这个(more info here):
// this is how you get user manager from OwinContext
var userManager = System.Web.HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
// Get ApplicationUser from UserManager
ApplicationUser user = UserManager.FindById(User.Identity.GetUserId());
如何访问当前用户以授权他在特定的
业务层的功能?
如果您需要访问服务中的当前用户,可以通过或注入。使用 ninject,您可以将UserId 注入到服务中:
kernel.Bind<MyService>().ToConstructor(ctorArg => new MyService(
HttpContext.Current.User.Identity.GetUserId<long>()).InRequestScope();
这就是MyService 类的样子:
public class MyService
{
private readonly long _userId;
public MyService(long userId)
{
// this service always has access to current user (if logged in)
_userId = userId;
}
// more code...
我不确定你的授权过程是什么... ASP.NET Identity,已经为你实现了授权任务。这是在 ASP.NET MVC 默认模板附带的 ApplicationUserManager 和 ApplicationSignInManager 中实现的。您可以在您的操作/类上使用[Authorize] 属性来防止未经授权的访问:
[Authorize] // <-- restricts all action methods of the class, unless marked [AllowAnonymous]
public class MyController : Controller
{
[HttpPost]
[Authorize] // <-- restricts this particular action method
public ActionResult MyAction(long id)
{
// do some action which requires authorization
}
关于 DDD 层,看看这个this link,它解释了属于每个层的服务。