我有一个使用 Asp.Net Identity 2.0 的 MVC 5 项目。我也在使用通用存储库模式。作为数据库模式的一部分,我有各种表的字段,这些表存储插入/更新/删除用户的用户 ID。因此,我想至少将用户对象或用户 ID 传递给通用存储库,以便在修改记录时使用。
但是,由于我无法直接在存储库类中访问身份,因此我试图在存储库实例化时传递它。它看起来像这样:
using System.Data.Entity;
using System.Threading.Tasks;
using System.Net;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using My.Models;
namespace My.Controllers
{
[Authorize]
public class FooController : MasterController
{
private IGenericRepositoryAsync<Topic> _repository;
public FooController()
{
//Point A
_repository = new GenericRepositoryAsync<Foo>(User.Identity);
}
public async Foo<ActionResult> Index()
{
//POINT B
//_repository = new GenericRepositoryAsync<Foo>(User.Identity);
return View(await _repository.GetAllAsync());
}
}
}
作为“A 点”的授权用户,User.Identity 为空,在//B 点它不为空,但我不想在每个 Controller 操作中都放置存储库初始化器。
感谢您的帮助和反馈。
最佳答案
Web Api 解决方案
您可以创建您的授权过滤器类,然后将 userId 添加到请求属性集合中:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
public override async Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
{
if (actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any()) return;
base.OnAuthorization(actionContext);
Guid userId;
if (actionContext.RequestContext.Principal.Identity.IsAuthenticated
&& Guid.TryParse(actionContext.RequestContext.Principal.Identity.GetUserId(), out userId))
{
actionContext.Request.Properties.Add("userId", actionContext.RequestContext.Principal.Identity.GetUserId());
}
}
}
一旦该类存在,您必须像这样在应用程序启动类(Global.asax web_start、Startup.cs)上添加此过滤器:
config.Filters.Add(new MyAuthorizeAttribute());
对于 Owin Startup.cs 将是这样的:
public void Configuration(IAppBuilder app)
{
ConfigureOAuth(app);
HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);
config.Filters.Add(new MyAuthorizeAttribute());
}
然后,在您的 Controller 中,您将能够获取 userId 正在执行的操作:
Guid userId = (Guid) ActionContext.Request.Properties["userId"];
MVC 解决方案
对于直接在 Controller 上使用 MVC:
using Microsoft.AspNet.Identity;
...
User.Identity.GetUserId();
或者在 Web Api 解决方案中添加过滤器:
public override void OnAuthorization(AuthorizationContext filterContext)
{
...
Guid userId = filterContext.HttpContext.User.Identity.Name.GetUserId();
...
}
关于c# - 身份 2.0 用户身份在 MVC 5 Controller 初始化程序中为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25908209/