如何访问在某个控制器中创建的 Viewbag 中的项目并在另一个控制器中使用它?

How to access item in Viewbag created in a certain controller and use it in another?

我从这样的 HomeController 在 ViewBag 中创建了一个项目。

ViewBag.RMessage = "You have been redirected to Login Page";

我想从我的 Login.cshtml 访问它。

这可能吗?如果是,怎么做?

您可以像下面这样使用会话:

在您的 startup 中,您可以添加:

    public void ConfigureServices(IServiceCollection services)
    {

        services.AddSession();

        //....
    }
   public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        //...
        app.UseSession();
        //...
     }

然后在你的 Homecontroller:

public class HomeController : Controller
{
   
    public IActionResult Index()
    {
        //set session

        HttpContext.Session.SetString("RMessage", "You have been redirected to Login Page");
        return View();
    }
    }

然后在您的 Login 视图中,您可以通过以下方式获取它:

@using Microsoft.AspNetCore.Http

//...
RMessage: @Context.Session.GetString("RMessage")

更详细的可以看文档:Session and state management in ASP.NET Core.