c# - 有类似 "RewriteToAction"的东西吗?

标签 c# asp.net .net asp.net-mvc asp.net-mvc-4

知道RedirectToAction ,我一直在寻找类似的东西来为用户保持 URL 稳定,并将责任从一个 Action 转移到另一个 Action 。

自从我找到zero Google results关于这个话题,我不妨完全尝试解决一个XY problem .

不过,我会尝试解释为什么我认为可能需要这样做。

场景:

public ActionResult A(int id)
{
    var uniqueID = CalculateUniqueFromId(id);

    // This compiles.
    return RedirectToAction("B", new { uniqueID });

    // This does not compile.
    return RewriteToAction("B", new { uniqueID });
}

public ActionResult B(Guid uniqueID)
{
    var model = DoCreateModelForUnique(uniqueID);
    return View("B", model);
}

在上面的代码中,action A 从一个整数计算出一个 guid,并将它传递给另一个 action。

解决方法:

我可以将上面的代码改成这样:

public ActionResult A(int id)
{
    var uniqueID = CalculateUniqueFromId(id);
    var model = DoCreateModelForUnique(uniqueID);

    return View("B", model);
}

public ActionResult B(Guid uniqueID)
{
    var model = DoCreateModelForUnique(uniqueID);
    return View("B", model);
}

这会按预期工作。

不过,在更复杂的情况下,我还是希望时不时地使用“服务器端重定向”(又名重写)。

替代解决方法:

我也可以使用 HttpContext.RewritePath ,例如在 Global.asax 的 Application_BeginRequest 中进行重写。

我觉得这“脱离了 MVC 上下文”,尽管它按预期工作。

我的问题:

是否有一种优雅的 MVC 集成方式来执行类似 RewriteToAction 的操作?

更新 1:

Luke commented一个有前途的链接:

How to simulate Server.Transfer in ASP.NET MVC?

我会尝试调查这是否符合我的需求。

最佳答案

怎么样

public ActionResult A(int id)
{
    var uniqueID = CalculateUniqueFromId(id);

    return B(uniqueID);
}

public ActionResult B(Guid uniqueID)
{
    var model = DoCreateModelForUnique(uniqueID);
    return View("B", model);
}

?

关于c# - 有类似 "RewriteToAction"的东西吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43467215/

相关文章:

javascript - ASP.NET 用户在线状态存储

c# - 二十一点纸牌、字符串或整数的数组?

c# - 使用 EntityFramework(数据库优先)方法的 DataAnnotations

c# - toTitleCase 忽略 C# 中的序数

javascript - 从 Javascript 到 C# 获取正确的日期(以毫秒为单位)

c# - .net 对象资源管理器控件

html - Email Blast HTML 大小问题

c# - 如何检查字符串是否包含超过 50 个字符的单词?

javascript - CKEditor baseHref 不工作,编辑器在缩小/捆绑后不工作

c# - 忽略多个标准不起作用的问题