C# 使用 AttributeRouting 在 WebAPI 中指定默认控制器/操作路由
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16265653/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Specify default controller/action route in WebAPI using AttributeRouting
提问by Abhijeet Patel
How does one set the default controller to use when using AttributeRouting instead of the default RouteConfiguration that WebAPI uses. i.e. get rid of the commented code section since this is redundant when using AttribteRouting
当使用 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 }
//);
}
}
If I comment the section above and try to run the webapi app, I get the following error since there is no default Home controller/action defined. HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents of this directory.
如果我评论上面的部分并尝试运行 webapi 应用程序,我会收到以下错误,因为没有定义默认的 Home 控制器/操作。 HTTP 错误 403.14 - Forbidden Web 服务器配置为不列出此目录的内容。
How can I specify the route via Attribute routing for the Home controller/action?
如何通过 Home 控制器/动作的属性路由指定路由?
EDIT: Code Sample:
编辑:代码示例:
public class HomeController : Controller
{
[GET("")]
public ActionResult Index()
{
return View();
}
public ActionResult Help()
{
var explorer = GlobalConfiguration.Configuration.Services.GetApiExplorer();
return View(new ApiModel(explorer));
}
}
回答by Kiran Challa
Have you tried the following:
您是否尝试过以下操作:
//[RoutePrefix("")]
public class HomeController : Controller
{
[GET("")]
public ActionResult Index()
{
return View();
}
}
This will add a route in the collection with url template as "" and defaults for controller and action to be "Home" and "Index" respectively.
这将在集合中添加一个路由,url 模板为“”,控制器和动作的默认值分别为“Home”和“Index”。
回答by Pete Klein
You need to install AttributeRouting (ASP.NET MVC)alongside AttributeRouting (ASP.NET Web API)that you have already installed.
您需要在已经安装的AttributeRouting (ASP.NET Web API)旁边安装AttributeRouting (ASP.NET MVC)。
The MVC and Web API packages are complimentary packages. Both dependent on the AttributeRouting.Core.* packages. AR for MVC is for routes on Controller methods; AR for Web API is for routes on ApiController methods.
MVC 和 Web API 包是免费包。两者都依赖于 AttributeRouting.Core.* 包。MVC 的 AR 用于控制器方法上的路由;AR for Web API 用于 ApiController 方法上的路由。
回答by Sajjan Sarkar
This worked for me. Add this to Register()in WebApiConfigclass
这对我有用。Register()在WebApiConfig课堂上添加这个
config.Routes.MapHttpRoute(
name: "AppLaunch",
routeTemplate: "",
defaults: new
{
controller = "Home",
action = "Get"
}
);
回答by Somad
Enable the attribute routing in your WebApiConfig class located in the App_Start folder by putting the following code:
通过放置以下代码,在位于 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.
}
}
}
You can combine with the convention-based attribute:
您可以结合基于约定的属性:
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 }
);
}
}
Now go to your global.asax class and add the following line of code:
现在转到 global.asax 类并添加以下代码行:
GlobalConfiguration.Configure(WebApiConfig.Register);
Your HomeController is an MVC controller. Try creating an API controller(let's say a CustomersController) and add your route attributes as follows:
您的 HomeController 是一个 MVC 控制器。尝试创建一个 API 控制器(假设是一个 CustomerController)并添加您的路由属性,如下所示:
[RoutePrefix("api/Product")]
public class CustomersController : ApiController
{
[Route("{customerName}/{customerID:int}/GetCreditCustomer")]
public IEnumerable<uspSelectCreditCustomer> GetCreditCustomer(string customerName, int customerID)
{
...
}
Hope it helps
希望能帮助到你
回答by Zeeshan Allauddin
A standard MVC application can have both MVC and Webapi support if you check both MVC and Webapi from the Create New Asp.net web application template.
如果您从创建新的 Asp.net Web 应用程序模板中选中 MVC 和 Webapi,则标准 MVC 应用程序可以同时具有 MVC 和 Webapi 支持。
You will need to do the following under RouteConfig.cs as your query is particular to MVC routes and not webapi ones:
您需要在 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 });
}
}
Notice the line with "routes.MapMvcAttributeRoutes();" which provides attribute routes while the call to "routes.MapRoute(...)" should provide you with a conventional route to a default controller and action.
注意带有“routes.MapMvcAttributeRoutes();”的那一行 它提供了属性路由,而对“routes.MapRoute(...)”的调用应该为您提供到默认控制器和操作的常规路由。
This is because attribute routing and conventional routing can be mixed. Hope that helps.
这是因为属性路由和常规路由可以混合使用。希望有帮助。

