0

我正在使用 Windows Auth,它在这个 odata 控制器上运行良好。但是在我得到最新的 NuGet 包(prerelease 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();
}

...
}

其他详情:

  • .NET 4.5
  • 网络表格

此外,当我恢复到 5.0.0.beta2 时,没有任何其他更改,它再次工作。所以这绝对是一个变化Microsoft.AspNet.WebApi。我可以更改代码,我只需要一些提示。谢谢!

4

1 回答 1

1

这是因为您在控制器构造函数中使用了 ApiController.User 。当时,该属性尚未初始化。你应该:

  • 在控制器上添加 [Authorize] 属性
  • 在 Initialize 方法中移动初始化代码

所以代码看起来像:

[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);
    }
}
于 2013-10-08T22:22:23.973 回答