ASP.NET MVC重點教程一周年版 第二回 UrlRouting

來源:互聯網
上載者:User

一、什麼是UrlRouting

你可以使用UrlRouting來配置一些URL的映射,使使用者可以按你的規則來訪問網站.

使用UrlRouting,一定要規定URL模式,它包括一個位置標識,它將在你請求網頁時按這個規則返 回給你內容. 當然,這個建立的規則完全是由你自己定義的.

上回說道如何訪問index.aspx 及about.aspx:

但是http://localhost/Views/Home/Index.aspx和 http://localhost/Views/Home/About.aspx這兩個地址並無法直接存取以下兩個檔案:

Views/Home/Index.aspx 與 Views/Home/About.aspx

這是怎麼回事呢,那我們要怎 樣才能訪問呢 ?

答案是:

http://localhost/Home和 http://localhost/Home/About

這是為什麼呢?

這就是UrlRouting的功能,而這個 功能的配置是由,URL的請求規則定義的,這個規則定義在Global.asax.cs中定義。

二、基 本UrlRouting規則的定義

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace MvcApplication2
{
  /// <summary>
  /// 還是老規矩,按序號看
  /// </summary>
  // Note: For instructions on enabling IIS6 or IIS7 classic mode,
  // visit http://go.microsoft.com/?LinkId=9394801
  public class MvcApplication : System.Web.HttpApplication
  {
    // 4.注意: 將1標的規則更改為 "{controller}.mvc/{action}/{id}" 即 可
    // 自行支援 IIS6 and IIS7 兩種模式
    // 筆者注:一般的虛擬機器主機不支援.mvc,.aspx也要檢查檔案存在
    // 變通方法為可以將.mvc換成.ashx或.asbx

    public static void RegisterRoutes(RouteCollection routes)
    {
      //5、此路徑不受後面規則控制
      routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
      //1、大家可以回憶一下Controller和Action的定義
      //因為MVC與傳統Aspx的最大不同就是訪問是
      //訪問的Controller.Action即某類下的一個函數而不是aspx檔案,
      //要展現給使用者哪一個aspx檔案是由Controller決定的(即預設的同名規則)
      //這個是檔案預設內建的UrlRouting規則,是將Controller/Action/id的訪問
      //模式指向對應的Controller及Action
      routes.MapRoute(
        "Default",                       //  Route 名稱
        "{controller}/{action}/{id}",              //  URL參數
        new { controller = "Home", action =  "Index", id = "" }
        // 2、參數的預設值也就是如果各部分為空白的話訪問
        //HomeController下的Index這個Action
      );
    }
    protected void Application_Start()
    { //3.這個沒什麼好講了,就是在應用程式啟動時初始化它
      RegisterRoutes(RouteTable.Routes);
    }
  }
}

注意這一點ASP.NET MVC 中URLRouting只與Controller/Action有關

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.