asp.net – RedirectToAction替代方案

我正在使用ASP.NET MVC 3.

我按照以下方式编写了一个帮助类:

public static string NewsList(this UrlHelper helper)
{
     return helper.Action("List","News");
}

在我的控制器代码中我使用它像这样:

return RedirectToAction(Url.NewsList());

所以在重定向之后,链接看起来像这样:

../News/News/List

RedirectToAction有替代品吗?有没有更好的方法来实现我的帮助方法NewsList?

解决方法

其实你真的不需要帮手:

return RedirectToAction("List","News");

或者如果你想避免硬编码:

public static object NewsList(this UrlHelper helper)
{
     return new { action = "List",controller = "News" };
}

然后:

return RedirectToRoute(Url.NewsList());

或另一种可能性是使用MVCContrib,它允许你写下面的内容(个人这就是我喜欢和使用的):

return this.RedirectToAction<NewsController>(x => x.List());

或另一种可能性是使用T4 templates.

因此,你可以自己选择和玩.

更新:

public static class ControllerExtensions
{
    public static RedirectToRouteResult RedirectToNewsList(this Controller controller)
    {
        return controller.RedirectToAction<NewsController>(x => x.List());
    }
}

然后:

public ActionResult Foo()
{
    return this.RedirectToNewsList();
}

更新2:

NewsList扩展方法的单元测试示例:

[TestMethod]
public void NewsList_Should_Construct_Route_Values_For_The_List_Action_On_The_News_Controller()
{
    // act
    var actual = UrlExtensions.NewsList(null);

    // assert
    var routes = new RouteValueDictionary(actual);
    Assert.AreEqual("List",routes["action"]);
    Assert.AreEqual("News",routes["controller"]);
}

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....