简体   繁体   中英

HTTP Error 404.0 - Not Found — MVC Attribute Routing

I'm trying to learn MVC 5 attribute routing.

I have enabled attribute routing

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 }
                );
            }
        }
    }

I have defined attribute routing in the MoviesController.cs File

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);
        }
    }
}

Still i keep getting

HTTP Error 404.0 - Not Found for URLs like

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

You've missed one bracket in regex. Instead of "released/{year}/{month:regex(\\d{2)}" it should be "Movies/released/{year}/{month:regex(\\d{2})}" .

So the following attribute will work:

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

As per @Random answer, the issue of 404 not found has been resolved. But in order to solve the number of digits constraint not getting applied on your route, your regex should look like this:

{month:regex(^\\d{2}$)}

In this ^ and $ mark the start and the end of the string.

Your original regex for month matches 2 digits anywhere but doesn't require it to be only 2 digits.

Is it not required to start the route with the controller's name

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

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