【问题标题】:odata ApiController.User == NULL after upgrade to web api 5.0.0-rc1odata ApiController.User == 升级到 web api 5.0.0-rc1 后为 NULL
【发布时间】:2013-10-08 13:53:13
【问题描述】:

我正在使用 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();
}

...
}

其他细节:

  • .NET 4.5
  • 网络表单

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

【问题讨论】:

    标签: webforms asp.net-web-api windows-authentication


    【解决方案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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-25
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 2017-01-29
      • 2013-08-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多