【发布时间】:2011-10-18 21:18:27
【问题描述】:
我有一个控制器,它继承自一个抽象的安全控制器,该控制器持有一个用户对象,如下所示。
public new User User
{
get
{
if (this.user == null)
{
var id = int.Parse(base.User.Identity.Name, CultureInfo.InvariantCulture);
this.user = this.UserRepository.FindById(id);
}
return this.user;
}
}
每次调用以下函数时,我都会收到上述 this.UserRepository 的空异常
[UrlRoute(Path = "api/stats/events/visits/accounttype/{idList}")]
[UrlRoute(Path = "api/{idList}/stats/events/visits/accounttype")]
[UrlRouteParameterDefault(Name = "idList", Value = "")]
public virtual ActionResult Vsat(string idList, DateTime? startDate, DateTime? endDate)
{
// get the ids from the url and retrieve a list of events for those user/s
var ids = (from id in idList.Split(',') where !string.IsNullOrEmpty(id) select Convert.ToInt64(id)).ToList();
var allEvents = this.eventRepository.FindForCompanyBetweenDatesForUsers(
this.User.Company.Id, new List<EventType> { EventType.Visit }, startDate, endDate, ids).ToList();
var groupResults = allEvents.GroupBy(x => x.Account.AccountType.Name);
return null;
}
即使我的 Api 构造函数像这样调用 Secure Controller 的基本构造函数
public ApiController(IUserRepository userRepository) : base(userRepository)
{
}
protected SecureController(IUserRepository userRepository)
{
this.UserRepository = userRepository;
}
更奇怪的是,页面上还有其他引用this.User的函数,它们都没有返回null相同的异常。他们点击了安全构造函数,然后是 api 构造函数,然后是函数。 上面的 Vsat 函数(仅出于测试目的而命名)命中函数,然后在行上中断
this.user = this.UserRepository.FindById(id);
除此之外,如果我在上面放置一个类似的函数,它可以工作,但是新的函数会出现同样的问题。
编辑
创建了一个新类,该功能完美运行。
public class TestController : SecureController
{
private readonly IEventRepository eventRepository;
public TestController(IUserRepository userRepository, IEventRepository eventRepository) : base(userRepository)
{
this.eventRepository = eventRepository;
}
[UrlRoute(Path = "test/stats/events/visits/accounttype/{idList}")]
[UrlRoute(Path = "test/{idList}/stats/events/visits/accounttype")]
[UrlRouteParameterDefault(Name = "idList", Value = "")]
public virtual ActionResult Vsat(string idList, DateTime? startDate, DateTime? endDate)
{
// get the ids from the url and retrieve a list of events for those user/s
var ids = (from id in idList.Split(',') where !string.IsNullOrEmpty(id) select Convert.ToInt64(id)).ToList();
var allEvents = this.eventRepository.FindForCompanyBetweenDatesForUsers(
this.User.Company.Id, new List<EventType> {EventType.Visit}, startDate, endDate, ids).ToList();
var groupResults = allEvents.GroupBy(x => x.Account.AccountType.Name);
return null;
}
}
【问题讨论】:
-
你能把问题隔离成一个更简单、可重现的测试用例吗?
-
我更新了帖子,希望这就是你的意思
-
@JLevett 我相信这可能只是您的基本构造函数在某些情况下被赋予空引用的简单案例。在
UserRespository属性设置器上,尝试测试传入的value(if (value == null) throw new Exception("null! why?");),如果它为 null,则抛出特定异常,仅用于完整性检查。
标签: c# asp.net-mvc