[英]Is there a way to redirect to a new page is System.NullReferenceException is triggered?
我将我的代码配置为从 asp.net 身份中提取用户 ID,然后检查它是否与候选 ID 相关联以加载该用户的查看候选页面。
自然,如果候选 id 是 null,它会抛出异常。
我有没有办法告诉 controller 如果抛出异常重定向到新操作?
我已经尝试过 if (candidate.CandidateId < 1 || Candidate.CandidateId.ToString() == null) 之类的 if 语句,但无论哪种方式都会弹出异常,因为候选 ID 是 null。
听起来你想得太多了。 这里真的没有理由涉及异常处理,也不应该依赖异常处理来处理应用程序逻辑。
如果问题是candidate
者是null
,那么检查candidate
者是否是null
:
if (candidate == null)
{
// perform redirect and return
}
// the rest of your logic relying on candidate
在问题中,您 state 实际上是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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.