首页 > 解决方案 > HTTP 错误 404.0 - 未找到 - MVC 属性路由

问题描述

我正在尝试学习 MVC 5 属性路由。

我启用了属性路由

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

    namespace Vidly
    {
        public class RouteConfig
        {
            public static void RegisterRoutes(RouteCollection routes)
            {
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
                routes.MapMvcAttributeRoutes();
                routes.MapRoute(
                    name: "Default",
                    url: "{controller}/{action}/{id}",
                    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
                );
            }
        }
    }

我在MoviesController.cs文件中定义了属性路由

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Vidly.Models;

namespace Vidly.Controllers
{
    public class MoviesController : Controller
    {
        // GET: Movies
        public ActionResult Random()
        {
            var movie = new Movie() { Name = "Shrek!" };
            //return View(movie);
            // return Content("Hello World");
            // return HttpNotFound();
            //return new EmptyResult();
            return RedirectToAction("Index", "Home", new { page = 1, sortBy = "name" });
        }
        public ActionResult Edit(int id)
        {
            return Content("id=" + id);
        }
        [Route("Movies/released/{year}/{month:regex(\\d{2)}")]
        public ActionResult ByReleaseYear(int year,int month)
        {
            return Content(year+"/"+ month);
        }
    }
}

我仍然不断得到

HTTP 错误 404.0 - 找不到 类似的 URL

http://localhost:51946/Movies/released/1243/12

标签: c#.netasp.net-mvc

解决方案


您错过了正则表达式中的一个括号。而不是"released/{year}/{month:regex(\\d{2)}"应该是"Movies/released/{year}/{month:regex(\\d{2})}".

因此,以下属性将起作用:

[Route("Movies/released/{year}/{month:regex(\\d{2})}")]

推荐阅读