简体   繁体   English

有没有办法重定向到新页面是 System.NullReferenceException 被触发?

[英]Is there a way to redirect to a new page is System.NullReferenceException is triggered?

I have my code configured in a way that it pulls the userid from asp.net identity and then checks to see if it's associated with a candidate id to load the view candidate page for that user.我将我的代码配置为从 asp.net 身份中提取用户 ID,然后检查它是否与候选 ID 相关联以加载该用户的查看候选页面。

Naturally, if that candidate id is null, it throws the exception.自然,如果候选 id 是 null,它会抛出异常。

Is there a way for me to tell the controller that if that exception is thrown redirect to new action?我有没有办法告诉 controller 如果抛出异常重定向到新操作?

I've tried if statements like If (candidate.CandidateId < 1 || candidate.CandidateId.ToString() == null), but either way that exception pops because candidate Id is null.我已经尝试过 if (candidate.CandidateId < 1 || Candidate.CandidateId.ToString() == null) 之类的 if 语句,但无论哪种方式都会弹出异常,因为候选 ID 是 null。

It sounds like you're drastically overthinking it.听起来你想得太多了。 There's really no reason to involve exception handling here, and one shouldn't rely on exception handling for application logic.这里真的没有理由涉及异常处理,也不应该依赖异常处理来处理应用程序逻辑。

If the problem is that candidate is null , then check if candidate is null :如果问题是candidate者是null ,那么检查candidate者是否是null

if (candidate == null)
{
    // perform redirect and return
}
// the rest of your logic relying on candidate

In the question you state that what's actually null is CandidateId .在问题中,您 state 实际上是nullCandidateId This sounds far less likely to me, but I suppose it may be possible in your setup.这对我来说听起来不太可能,但我想在你的设置中它可能是可能的。 If that's the case, the structure is still the same:如果是这样的话,结构还是一样的:

if (candidate.CandidateId == null)
{
    // perform redirect and return
}
// the rest of your logic relying on candidate.CandidateId

Or if CandidateId is a Nullable<T> :或者,如果CandidateIdNullable<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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM