[英]Redirect within an int class if error without changing class type
我是 c# 的新手,在嘗試設置特定 class 時遇到問題。
我的代碼中已經有很多 trycatch 和重定向,但我似乎無法得到以下部分,我知道問題是因為 class 是一個 int 並且應該是使用重定向的 ActionResult,但后來我得到了返回 int 時出錯。 我需要 class 為兩者工作。
我的 BaseController 中的當前 class 可以正常工作,我在大多數其他控制器上調用 GetUID();
public int GetUID()
{
return int.Parse(System.Web.HttpContext.Current.Session["UID"].ToString());
}
我遇到的問題是,如果某人的 session 超時,他們會收到錯誤消息,但我希望將他們重定向到登錄頁面。
所以我嘗試執行以下操作;
public int GetUID()
{
try
{
return int.Parse(System.Web.HttpContext.Current.Session["UID"].ToString());
}
catch(Exception)
{
return RedirectToAction("Login", "Account");
}
}
因為 class 是 int class 我在重定向時收到錯誤:“無法將類型'System.Web.Mvc.RedirectToRouteResult' 隱式轉換為”。
我也嘗試過以下操作;
public ActionResult GetUID()
{
try
{
return int.Parse(System.Web.HttpContext.Current.Session["UID"].ToString());
}
catch(Exception)
{
return RedirectToAction("Login", "Account");
}
}
但后來我得到相反的錯誤:“無法將類型'int'隱式轉換為'System.Web.Mvc.RedirectToRouteResult'”。
如果重定向到登錄頁面時出錯,有沒有辦法讓 class 返回一個 int BUT? 我看過 SO 和 Google,我可以看到很多關於從 View 轉換為 Action 等的查詢,但沒有類似的。 感謝任何幫助。
您必須定義並返回一個描述重定向操作的int
錯誤代碼,當您看到它時,您必須調用RedirectToAction
方法。
編輯:你不能返回不同的類型。 然后,或者您返回 object:
public object GetUID(){...}
在您的 BaseController 中,您可以執行以下操作:
object o = GetUID();
if (o is int UID)
//do your stuff
else if (o is ActionResult action)
//execute the action
另一種方法是定義錯誤代碼,例如負數是錯誤。 然后你將擁有:
public const int ReturnHomeError = -1;
public int GetUID()
{
try
{
return int.Parse(System.Web.HttpContext.Current.Session["UID"].ToString());
}
catch(Exception)
{
return ReturnHomeError;
}
}
在您的 BaseController 中,您可以執行以下操作:
int uid = GetUID();
switch(uid)
{
case ReturnHomeError:
//Call RedirectToAction("Login", "Account")
break;
default:
//Do your stuff
break;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.