简体   繁体   中英

URL redirecting to a new page in C#

A specific page in my web application has a URL www.example.com/Test/Index

However, I want to make this URL accessible when the user simply inputs www.example.com/Test instead of the whole thing.

So how can this be done using C# alone? Any help will be highly appreciated!

You can use a redirect. In ASP.NET this is Response.Redirect. In MVC this is RedirectToAction("Index"). This will cause their browser to then request the other URL.

If you want the URL to not be changed/redirected, and show www.example.com/Test , then you can use a server side redirect. ASP.NET: Server.Transfer. In MVC you can just return Index(); but this can be problematic sometimes. A better option is to use a default route:

public class MvcApplication : System.Web.HttpApplication
  {
...
    public static void RegisterRoutes(RouteCollection routes)
    {
      routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

      routes.MapRoute(
          "Default", // Route name
          "{controller}/{action}/{id}", // URL with parameters
          new { controller = "Test", action = "Index", id = UrlParameter.Optional } // Parameter defaults
      );

    }

You should get this code automatically with any newly created MVC 3 application. you just have to custimize it for the controller you want to respect this default route.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM