使用AttributeRouting在WebAPI中指定默认控制器/操作路由

如何设置使用AttributeRouting而不是WebAPI使用的默认RouteConfiguration时使用的默认控制器。 即删除注释的代码部分,因为使用AttribteRouting时这是多余的

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

如果我评论上面的部分并尝试运行webapi应用程序,我会收到以下错误,因为没有定义默认的Home控制器/操作。 HTTP错误403.14 – 禁止Web服务器配置为不列出此目录的内容。

如何通过归属控制器/操作的属性路由指定路由?

编辑:代码示例:

  public class HomeController : Controller { [GET("")] public ActionResult Index() { return View(); } public ActionResult Help() { var explorer = GlobalConfiguration.Configuration.Services.GetApiExplorer(); return View(new ApiModel(explorer)); } } 

您是否尝试过以下方法:

 //[RoutePrefix("")] public class HomeController : Controller { [GET("")] public ActionResult Index() { return View(); } } 

这将在集合中添加路径,其中url模板为“”,控制器和操作的默认值分别为“Home”和“Index”。

您需要安装AttributeRouting(ASP.NET MVC)以及已安装的AttributeRouting(ASP.NET Web API) 。

MVC和Web API包是免费软件包。 两者都依赖于AttributeRouting.Core。*包。 用于MVC的AR用于Controller方法的路由; AR for Web API用于ApiController方法上的路由。

这对我有用。 将其添加到WebApiConfig类中的Register()

 config.Routes.MapHttpRoute( name: "AppLaunch", routeTemplate: "", defaults: new { controller = "Home", action = "Get" } ); 

通过输入以下代码,在App_Start文件夹中的WebApiConfig类中启用属性路由:

 using System.Web.Http; namespace MarwakoService { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API routes config.MapHttpAttributeRoutes(); // Other Web API configuration not shown. } } } 

您可以与基于约定的属性结合使用:

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

现在转到你的global.asax类并添加以下代码行:

 GlobalConfiguration.Configure(WebApiConfig.Register); 

您的HomeController是一个MVC控制器。 尝试创建一个API控制器(比如说一个CustomersController)并添加你的路由属性,如下所示:

 [RoutePrefix("api/Product")] public class CustomersController : ApiController { [Route("{customerName}/{customerID:int}/GetCreditCustomer")] public IEnumerable GetCreditCustomer(string customerName, int customerID) { ... } 

希望能帮助到你

如果从Create New Asp.net Web应用程序模板中检查MVC和Webapi,则标准MVC应用程序可以同时支持MVC和Webapi。

您需要在RouteConfig.cs下执行以下操作,因为您的查询特定于MVC路由而不是webapi路由:

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

注意带有“routes.MapMvcAttributeRoutes();”的行。 它提供属性路由,而对“routes.MapRoute(…)”的调用应该为您提供到默认控制器和操作的传统路径。

这是因为属性路由和传统路由可以混合使用。 希望有所帮助。