MVC 5 Web Attribute Routing is not working

2019-07-26 09:20发布

I implemented the Attribute routing in my Application and after that when I started nothing was working as planned. Only the Json Results works rest is not working as expected.

 [RoutePrefix("ProductCategory")]
    public class CategoryController : Controller
    {
      [Route("CategoryMain")]
        // GET: /Category/
        public ActionResult Index()
        {
            var cat = categoryService.GetCategories();

            if (Request.IsAjaxRequest())
            {
                return PartialView("Index", cat);
            }
            return View("Index", cat);
        }
    }

Error

Server Error in '/' Application. The resource cannot be found. Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.

Requested URL: /ProductCategory/MainIndex I've also tried with Just Index even that is not working now

But if The method is JsonResult it will return me the data in json format. Its not working on any other ActionResults My 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 = "Category", action = "Index", id = UrlParameter.Optional }
            );


        }

My webapiConfig

public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }

My Global

 AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

        // Autofac and Automapper configurations
        Bootstrapper.Run();

1条回答
仙女界的扛把子
2楼-- · 2019-07-26 09:46

Given the route prefix and route below

[RoutePrefix("ProductCategory")]
public class CategoryController : Controller {
    [HttpGet]
    [Route("CategoryMain")] // Matches GET ProductCategory/CategoryMain
    public ActionResult Index() {
        var cat = categoryService.GetCategories();
        if (Request.IsAjaxRequest()) {
            return PartialView("Index", cat);
        }
        return View("Index", cat);
    }
}

The requested URL needs to be

ProductCategory/CategoryMain

for the CategoryController.Index Action

查看更多
登录 后发表回答