我正在使用Windows Auth,它在这个odata控制器上工作正常。但是在我得到最新的NuGet包(预发布5.0.0-rc1)之后发生了一些变化,ApiController.User
为空。它不再通过Windows Auth了。有任何想法吗?我尝试添加[Authorize]属性,但这不起作用 - 可能在其他地方需要更多配置。
public class ProductsController : EntitySetController<Product, int>
{
protected ProjectContextUnitOfWork UoW;
protected UserRepository UserRepo;
protected ProductRepository ProductRepo;
protected Project.Models.User CurrentUser;
// odata/Products/
public ProductsController()
{
if (!User.Identity.IsAuthenticated)
{
HttpResponseMessage msg = Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "User not authenticated.");
throw new HttpResponseException(msg);
}
ProjectUserPrincipal LoggedInUser = this.User as ProjectUserPrincipal;
// - closed in Dispose()
UoW = new ProjectContextUnitOfWork(false); //without lazy loading
UserRepo = new UserRepository(UoW);
ProductRepo = new ProductRepository(UoW);
CurrentUser = UserRepo.Get(LoggedInUser.Username, LoggedInUser.Domain);
}
protected override Product GetEntityByKey(int id)
{
var x = from b in ProductRepo.GetAvailableProductsWithNumbers(CurrentUser)
where b.Id == id
select b;
return x.FirstOrDefault();
}
...
}
其他细节:
此外,当我恢复到5.0.0.beta2时,没有任何其他更改,它再次起作用。所以这绝对是Microsoft.AspNet.WebApi
的变化。我可以更改代码,我只需要一些提示。谢谢!
答案 0 :(得分:1)
这是因为您在控制器构造函数中使用ApiController.User。那时,该物业尚未初始化。你应该:
所以代码如下:
[Authorize]
public class ProductsController : EntitySetController<Product, int>
{
protected override void Initialize(System.Web.Http.Controllers.HttpControllerContext controllerContext)
{
base.Initialize(controllerContext);
ProjectUserPrincipal LoggedInUser = this.User as ProjectUserPrincipal;
// - closed in Dispose()
UoW = new ProjectContextUnitOfWork(false); //without lazy loading
UserRepo = new UserRepository(UoW);
ProductRepo = new ProductRepository(UoW);
CurrentUser = UserRepo.Get(LoggedInUser.Username, LoggedInUser.Domain);
}
}