【小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 的参数传递。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
根据提供的引用内容,可以看出这是一个dotnet项目,而不是Visual Studio Code C#项目。因此,我将为您提供如何在dotnet项目中设置路由规则的答案。 在dotnet项目中设置路由规则需要进行以下步骤: 1. 在项目中添加Microsoft.AspNetCore.Mvc.Core NuGet包,以便使用MVC框架。 2. 在Startup.cs文件中添加以下代码,以启用MVC框架并配置路由规则: ```csharp using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace YourProjectName { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } } ``` 3. 在Controllers文件夹中创建控制器,并添加以下代码,以设置路由规则: ```csharp using Microsoft.AspNetCore.Mvc; namespace YourProjectName.Controllers { public class HomeController : Controller { public IActionResult Index() { return View(); } [Route("your-route")] public IActionResult YourAction() { return View(); } } } ``` 在上面的代码中,我们使用[Route]属性来设置路由规则。例如,[Route("your-route")]将路由设置为“your-route”。 4. 在Views文件夹中创建视图,并使用以下代码,以设置视图的路由规则: ```html @{ ViewData["Title"] = "Your View"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h1>Your View</h1> ``` 在上面的代码中,我们没有设置视图的路由规则,因为它将自动与控制器的路由规则匹配。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

全栈小5

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

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

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

打赏作者

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

抵扣说明:

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

余额充值