How can I properly handle 404 in ASP.NET MVC?

后端 未结 19 2693
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-21 10:14

I am using RC2

Using URL Routing:

routes.MapRoute(
    \"Error\",
     \"{*url}\",
     new { controller = \"Errors\", action = \"N         


        
19条回答
  •  有刺的猬
    2020-11-21 10:34

    In MVC4 WebAPI 404 can be handle in the following way,

    COURSES APICONTROLLER

        // GET /api/courses/5
        public HttpResponseMessage Get(int id)
        {
            HttpResponseMessage resp = null;
    
            var aCourse = _courses.Where(c => c.Id == id).FirstOrDefault();
    
            resp = aCourse == null ? new HttpResponseMessage(System.Net.HttpStatusCode.NotFound) : new HttpResponseMessage(aCourse);
    
            return resp;
        }
    

    HOME CONTROLLER

    public ActionResult Course(int id)
    {
        return View(id);
    }
    

    VIEW

    GLOBAL

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
        routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    
        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
    

    RESULTS

    enter image description here

提交回复
热议问题