c# - ASP.NET MVC 3 - 在 Post Redirect Get 工作流中检测当前页面是否被重定向到

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

在我的 C# .NET 4 MVC 3 应用程序中,我有一组 CRUD 页面的删除 Controller ,它使用 Post Redirect Get 模式在成功删除后重定向到 Index Controller 。仅当此页面未通过此类操作重定向到时,我才想在索引页面上呈现一个按钮。是否有一种简单的方法来检测当前页面是否被重定向到(即作为 PRG 重定向的结果到达)?

看完http://blog.simonlovely.com/archive/2008/11/26/post-redirect-get-pattern-in-mvc.aspx我目前的方法是在 DeleteMyEntity 方法成功后使用 TempData 在我的删除 Controller 中设置它:

try {
    MyService.DeleteMyEntity(MyViewModel.MyEntity);
    TempData["Redirected"] = true;
    args = new RouteValueDictionary(new { Foo = 1, Baa = 2 });
    return RedirectToAction("Index", args);
} catch (Exception e)
{
   //Logging etc. - redirect should never be reached on exception (and TempData item not set)
   throw(e);
}

然后在我的 Index Controller 中检查这个值是否存在并且是否为真:

if (TempData["Redirected"] != null)
{
    //we can then do something useful with this
}

我看到的另一个机会是将另一个项目添加到 args 并在 Controller 中检查它,但在这种情况下我也可以只使用 TempData。有没有一种方法可以在请求中使用 HTTP 响应代码来执行此操作,而无需通过 TempData 或类似机制传递此数据?

最佳答案

另一种方法是设置一个全局 Action 过滤器,为您“注入(inject)”该标志...

public class RedirectDetect: ActionFilterAttribute{
   public override void OnActionExecuted(ActionExecutedContext filterContext){
        if (filterContext.Result is RedirectToRouteResult ||
            filterContext.Result is RedirectResult)
        {
             TempData["Redirected"] = true;
             //or what ever other indicator you want to set
        }
   }
}

然后你可以调用 redirectToAction("Index") 然后检查你的接收处理程序

旁注:我挑战你大声说 RedirectDetect 而不是傻笑。

关于c# - ASP.NET MVC 3 - 在 Post Redirect Get 工作流中检测当前页面是否被重定向到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13594181/

相关文章:

asp.net - 为什么app.config和web.config同时存在?

asp.net-mvc - 在.Net C# MVC中打开下载的excel文件后文件名发生变化

c# - 使用正确的表格格式将带有图像的 DataGridView 数据导出到 Excel、HTML 或 Word

c# - 如何在 C# 中转换键和数组的集合?

asp.net - 防止使用邮政信箱地址的最佳策略?

asp.net - 如何获取 Visual Studio 'Publish' 选项以从 bin 目录中删除文件?

c# - ASP.NET:获取外部 IP 地址

c# - 是否有可能将马尔可夫链引导至某些关键字?

asp.net-mvc - 从 Mvc 3 View 填充 List<Objects>

asp.net-mvc-3 - MVC 3复杂的模型验证