簡體   English   中英

有沒有辦法重定向到新頁面是 System.NullReferenceException 被觸發?

[英]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 實際上是nullCandidateId 這對我來說聽起來不太可能,但我想在你的設置中它可能是可能的。 如果是這樣的話,結構還是一樣的:

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

或者,如果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