我的代码配置方式是,它从asp.net标识中提取用户id,然后检查它是否与候选id关联,以加载该用户的视图候选页面。
当然,如果候选id为null,它就会抛出异常。
有没有办法告诉控制器,如果抛出异常,重定向到新的操作?
我尝试过if(candidate.CandidateId<1||CandidateId.ToString((==null(之类的if语句,但无论哪种方式,都会弹出异常,因为CandidateId为null。
听起来你想得太多了。这里真的没有理由涉及异常处理,应用程序逻辑也不应该依赖异常处理。
如果问题是candidate
是null
,则检查candidate
是否是null
:
if (candidate == null)
{
// perform redirect and return
}
// the rest of your logic relying on candidate
在问题中,您指出实际上是null
的是CandidateId
。这听起来不太可能,但我想在你的设置中可能会发生。如果是这样的话,结构仍然是一样的:
if (candidate.CandidateId == null)
{
// perform redirect and return
}
// the rest of your logic relying on candidate.CandidateId
或者如果CandidateId
是Nullable<T>
:
if (!candidate.CandidateId.HasValue)
{
// perform redirect and return
}
// the rest of your logic relying on candidate.CandidateId