【小5聊】C# 遵守路由设置规则,否则报错

什么是路由,对于初学者来说确实会有点搞不清楚!

官方解释,ASP.NET 路由模块负责将传入浏览器请求映射到特定的 MVC 控制器操作

目录

什么是路由,对于初学者来说确实会有点搞不清楚!

1、路由设置

2、请求地址

3、错误写法

4、正确写法

5、官方默认写法

6、 使用自定义路由


1、路由设置

ASP.NET MVC,最大的一个特点就是引入了路由的概念。

以下是.net framework框架的路由设置

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

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

2、请求地址

假设请求地址为:/Area/Test/List/123

3、错误写法

不能直接使用TestID来接受参数

public async Task<ActionResult> TestItem(int TestID)
{
    return View();
}

4、正确写法

public async Task<ActionResult> TestItem(int id)
{
    int TestID = id;
    return View();
}

5、官方默认写法

Global.asax.cs

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

namespace MvcApplication1
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit https://go.microsoft.com/?LinkId=9394801

    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 = "Home", action = "Index", id = "" }  // Parameter defaults
            );
        }

        protected void Application_Start()
        {
            RegisterRoutes(RouteTable.Routes);
        }
    }
}

6、 使用自定义路由

添加到路由表的路由的顺序非常重要。 新的自定义博客路由在现有默认路由之前添加。 如果撤消了顺序,则默认路由将始终被调用,而不是自定义路由。

自定义博客路由与以 /Archive/开头的任何请求匹配。 因此,它匹配以下所有 URL:

  • /Archive/12-25-2009

  • /Archive/10-6-2004

  • /Archive/apple

自定义路由将传入请求映射到名为 Archive 的控制器,并调用 Entry () 操作。 调用 Entry () 方法时,条目日期将作为名为 entryDate 的参数传递。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

全栈小5

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值