MVC5中的Attributerouting无法正常工作

MVC5中的Attributerouting无法正常工作

本文介绍了MVC5中的Attributerouting无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I'm trying to use AttributeRouting but it seems like it is not going to work at all.





我的尝试:





What I have tried:

I have a navigation page(angularJS controller) from which it goes to a specific MVC controller:

    $scope.Department = function () {
		window.location.href = appSetting.publish + "/Settings/Departments";
	}

There is a `SettingsController` which is:


    public class SettingsController : Controller
	{
		public ActionResult Departments()
		{
			return View();
		}
	}

This works perfectly until I tried using this:

    $scope.Department = function () {
		window.location.href = appSetting.publish + "/appsettings/Departments";
	}

and the controller to this:

    [RoutePrefix("appsettings")]
	public class SettingsController : Controller
	{
		[Route("Departments")]
		public ActionResult Departments()
		{
			return View();
		}
	}

It goes to Http error 404 not found page.
I have referred this article(http://www.c-sharpcorner.com/UploadFile/b1df45/web-api-route-and-route-prefix-part-2/).

Also in global.asax class and added the following line of code:

    GlobalConfiguration.Configure(WebApiConfig.Register);


And in `WebApiConfig`:

    public static class WebApiConfig
    {
		public static void Register(HttpConfiguration config)
		{
			// Attribute routing.
			config.MapHttpAttributeRoutes();

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


And in `RouteConfig`:

    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 all these. I checked if I have AttributeRouting (ASP.NET MVC) alongside AttributeRouting (ASP.NET Web API) in NuGet package and both were not installed so I just tried with AttributeRouting (ASP.NET MVC) but it got me the same error. 

推荐答案



[HttpGet]
[Route("Departments")]
public ActionResult Departments()
{
    return View();
}


这篇关于MVC5中的Attributerouting无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 17:15