0

我是 c# 新手,在尝试设置特定类时遇到问题。

我的代码中已经有大量的 trycatch 和重定向,但我似乎无法得到以下部分,我知道问题是因为该类是一个 int 并且应该是使用重定向的 ActionResult,但后来我得到一个返回 int 时出错。我需要班级为两者工作。

我的 BaseController 中的当前类有效,我在大多数其他控制器上调用 GetUID();

    public int GetUID()
    {
        return int.Parse(System.Web.HttpContext.Current.Session["UID"].ToString());
    }

我遇到的问题是,如果某人的会话超时,他们会收到错误消息,但我希望他们被重定向到登录页面。

所以我尝试执行以下操作;

    public int GetUID()
    {
        try
        {
            return int.Parse(System.Web.HttpContext.Current.Session["UID"].ToString());
        }
        catch(Exception)
        {
            return RedirectToAction("Login", "Account");
        }
    }

因为该类是一个 int 类,所以重定向时出现错误:“无法将类型 'System.Web.Mvc.RedirectToRouteResult' 隐式转换为 'int'”。

我也尝试过以下操作;

    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'”。

如果重定向到登录页面时出错,有没有办法让类返回一个 int BUT?我看过 SO 和 Google,我可以看到很多关于从 View 转换为 Action 等的查询,但没有类似的。感谢任何帮助。

4

1 回答 1

1

您必须定义并返回int描述重定向操作的错误代码,当您看到它时,您必须调用RedirectToAction方法。

编辑: 你不能返回不同的类型。然后或者你返回一个对象:

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;
}
于 2020-04-19T15:47:10.587 回答