溫馨提示×

C#如何使用路由實現URL重定向

c#
小樊
161
2024-08-12 01:00:37
欄目: 編程語言

在C#中,可以使用ASP.NET MVC框架中的路由來實現URL重定向。下面是一個簡單示例:

using System.Web.Mvc;
using System.Web.Routing;

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Redirect",
            url: "old-url",
            defaults: new { controller = "Home", action = "RedirectToNewUrl" }
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

public class HomeController : Controller
{
    public ActionResult RedirectToNewUrl()
    {
        return RedirectPermanent("/new-url");
    }
}

在上面的示例中,首先在RouteConfig類中定義了兩個路由規則,其中一個用于重定向舊URL到新URL。在HomeController中的RedirectToNewUrl方法中,通過調用RedirectPermanent方法來執行重定向操作。

注意:在ASP.NET Core中,使用Startup類中的UseEndpoints方法來配置路由規則,實現方式略有不同,但原理類似。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女