簡體   English   中英

如何通過通用路由重定向

[英]How to redirect by common routing

我有行動

public ActionResult Edit(int id)

如果id為null,我需要重定向到操作索引。 如何在路由中做到這一點?

我試過了:

routes.MapRoute(
                name: "Redirect from empty controller/edit to controller/list",
                url: "{controller}/Edit",
                defaults: new { controller = "Home", action = "Index" }
            );

但這沒有幫助。

嗯不確定路由,但是如果有幫助的話,您可以使用return RedirectToAction("index", "home"); (其中index是您的操作方法,home是您要對其訪問的控制器)。

重定向很簡單。 您可以通過將id參數設置為可空值來檢查其是否存在。 您不需要路由配置。 當用戶向http://example.org/Home/Edit發送請求時,這會將用戶重定向到http://example.org/Home

public ActionResult Edit(int? id)
{
    if (id == null)
    {
        return RedirectToAction("Index");
    }

    //other logic
}

如果您不希望重定向並使Index操作使用http://example.org/Home/Edit URL響應請求,則可以創建如下路由:

routes.MapRoute("HomeEdit", 
                "Home/Edit", new {controller = "Home", action = "Index"});

只要確保此路由在RouteConfig中的默認路由之上即可。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM