【问题标题】:Remove serialized Model from URL of MVC controller action从 MVC 控制器操作的 URL 中删除序列化模型
【发布时间】:2015-06-22 17:01:36
【问题描述】:

在我的 Home 控制器中是 Index() 操作。在Index() 中,我使用当前经过身份验证的用户 ID 从数据库中返回一个用户对象:

return View(db.Users.Find(User.UserId));

正常工作,网址很简单:

https://localhost:44301/

然而,在 Home 控制器的其他地方,我在一个单独的操作中修改了当前用户并将其传递回索引视图,使用:

return RedirectToAction("Index", user);

当我这样做时,URL 会被用户模型的序列化版本弄得一团糟:

https://localhost:44301/Home/Index/4?Name=katrina&Administrator=True&PasswordEncodedHash=1000%3AqzWR8U6poGKshxHDsP%2B5yFhz5AZ01%2Fv1%3ASqCG0SliIpjX0M0jjkQqAf5aunTVS2gx&Tests=System.Collections.Generic.List%601%5BLearningManagementSystem.Models.Test%5D&UserTestAttempts=System.Collections.Generic.List%601%5BLearningManagementSystem.Models.UserTestAttempt%5D&Phones=System.Collections.Generic.List%601%5BLearningManagementSystem.Models.Phone%5D

我想我在重定向动作的方式上做了一些愚蠢的事情,但是我不知道如何解决这个问题。我尝试添加自定义路由,但“?Name=....”仍会附加到该路由。

(编辑)来自其他操作的代码:

public ActionResult ToggleAdministrator()
{
    if (Request.IsAuthenticated)
    {
        var user = db.Users.Find(User.UserId);
        user.Administrator = !user.Administrator;
        db.SaveChanges();

        Response.Cookies.Add(cookie);

        return RedirectToAction("Index", user);
    }

    return RedirectToAction("Index", (User)null);
}

【问题讨论】:

  • 请分享您希望用户重定向的操作代码。
  • 我已将其添加到问题中。
  • 希望我的回答能让您了解如何在 MVC 应用程序中处理重定向。

标签: c# asp.net-mvc asp.net-mvc-5


【解决方案1】:

我认为您不需要在使用 RedirectToAction 重定向到某些操作时传递整个数据。

假设您在Home controller 中有一个操作Index

Public ActionResult Index(int id)
{
  -- write the code here to fetch data based on that id
  -- like
     var user = db.Users.FirstOrDefault(x=>x.Id = id);
     return View(user);
}

现在,您只需要使用重定向到如下操作:

return RedirectToAction("Index", new { Id= 5 });

注意:

  • 切勿在 QueryString 或 GET 请求中传递复杂类型对象

【讨论】:

  • 您的回答让我意识到我是直接将参数传递给无参数的Index() 操作。哈哈愚蠢的错误,感谢您的帮助!
猜你喜欢
  • 2012-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-28
  • 1970-01-01
  • 1970-01-01
  • 2016-08-18
  • 1970-01-01
相关资源
最近更新 更多