C# MVC 属性路由不起作用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16944947/
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
MVC Attribute Routing Not Working
提问by Teagan42
I'm relatively new to the MVC framework but I do have a functioning Web Project with an API controller that utilizes AttributeRouting (NuGet package) - however, I'm starting another project and it just does not want to follow the routes I put in place.
我对 MVC 框架相对较新,但我确实有一个功能强大的 Web 项目,它带有一个利用 AttributeRouting(NuGet 包)的 API 控制器——但是,我正在启动另一个项目,它只是不想遵循我输入的路线地方。
Controller:
控制器:
public class BlazrController : ApiController
{
private readonly BlazrDBContext dbContext = null;
private readonly IAuthProvider authProvider = null;
public const String HEADER_APIKEY = "apikey";
public const String HEADER_USERNAME = "username";
private Boolean CheckSession()
{
IEnumerable<String> tmp = null;
List<String> apiKey = null;
List<String> userName = null;
if (!Request.Headers.TryGetValues(HEADER_APIKEY, out tmp)) return false;
apiKey = tmp.ToList();
if (!Request.Headers.TryGetValues(HEADER_USERNAME, out tmp)) return false;
userName = tmp.ToList();
for (int i = 0; i < Math.Min(apiKey.Count(), userName.Count()); i++)
if (!authProvider.IsValidKey(userName[i], apiKey[i])) return false;
return true;
}
public BlazrController(BlazrDBContext db, IAuthProvider auth)
{
dbContext = db;
authProvider = auth;
}
[GET("/api/q/users")]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
[GET("api/q/usersauth")]
public string GetAuth()
{
if (!CheckSession()) return "You are not authorized";
return "You are authorized";
}
}
AttributeRoutingConfig.cs
AttributeRoutingConfig.cs
public static class AttributeRoutingConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
// See http://github.com/mccalltd/AttributeRouting/wiki for more options.
// To debug routes locally using the built in ASP.NET development server, go to /routes.axd
routes.MapAttributeRoutes();
}
public static void Start()
{
RegisterRoutes(RouteTable.Routes);
}
}
Global.asax.cs:
Global.asax.cs:
// Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801
// 注意:有关启用 IIS6 或 IIS7 经典模式的说明,// 请访问http://go.microsoft.com/?LinkId=9394801
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
When I try to navigate to /api/q/users - I get a 404 not found error. If I change the routes to be "/api/blazr/users" - I get an error about multiple actions and not being able to determine which action to take.
当我尝试导航到 /api/q/users 时 - 我收到 404 not found 错误。如果我将路由更改为“/api/blazr/users” - 我会收到有关多个操作的错误,并且无法确定要执行的操作。
Any help is appreciated - I really just need a small nudge to figure out where the issue is, no need to solve it completely for me (I need to learn!)
任何帮助表示赞赏 - 我真的只需要一点点推动即可找出问题所在,无需为我完全解决它(我需要学习!)
Thanks
谢谢
EDIT
编辑
routes.axd:
路线.axd:
api/{controller}/{id}
{resource}.axd/{*pathInfo}
{controller}/{action}/{id}
回答by 4rchie
Ensure you have NuGet package "WebApp API" installed for AttributeRouting.
确保为 AttributeRouting 安装了 NuGet 包“WebApp API”。
回答by David McEleney
In your App_Start/RoutesConfig.cs
在你的 App_Start/RoutesConfig.cs
make sure you call the following line of code:
确保您调用以下代码行:
routes.MapMvcAttributeRoutes();
回答by Derreck Dean
Not only do you have to have the call to routes.MapMvcAttributeRoutes()in your App_Start\RouteConfig.csfile, it must appear beforedefining your default route! I add it before that and after ignoring {resource}.axd{*pathInfo}. Just found that out trying to get attribute routing to work correctly with my MVC 5 website.
您不仅必须routes.MapMvcAttributeRoutes()在App_Start\RouteConfig.cs文件中调用,而且必须在定义默认路由之前出现!我在这之前和之后添加它忽略{resource}.axd{*pathInfo}. 刚刚发现试图让属性路由与我的 MVC 5 网站正常工作。
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Account", action = "Index", id = UrlParameter.Optional }
);
}
回答by Boris Malaichik
In nuGet package manager install to your project Web API Web Host package
在 nuGet 包管理器中安装到你的项目 Web API Web Host 包
add this class to folder app_start-> WebApiConfig.cs(if it doesn't exits - create):
将此类添加到文件夹 app_start-> WebApiConfig.cs(如果它不存在 - 创建):
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes(); // pay attention to this method
//here you can map any mvc route
//config.Routes.MapHttpRoute(
// name: "DefaultApi",
// routeTemplate: "api/{controller}/{id}",
// defaults: new { id = RouteParameter.Optional }
//);
config.EnableSystemDiagnosticsTracing();
}
}
after Try change your Global.asax configuration to:
在尝试将您的 Global.asax 配置更改为:
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}
P.S.
聚苯乙烯
look through this article, very useful http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2
通读这篇文章,非常有用 http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2
cheers
干杯
回答by gdbj
I came here looking for answers related to RoutePrefix. After some testing, I found that simply adding a
我来这里是为了寻找与RoutePrefix. 经过一些测试,我发现只需添加一个
[RoutePrefix("MyPrefix")]
[RoutePrefix("MyPrefix")]
without using a subsequent Route attribute such as
不使用后续的 Route 属性,例如
[Route("MyRoute")]
[Route("MyRoute")]
means the RoutePrefix was ignored. Haack's routedebugger is very helpful in determining this: https://haacked.com/archive/2008/03/13/url-routing-debugger.aspx/
表示 RoutePrefix 被忽略。Haack 的 routedebugger 对确定这一点非常有帮助:https://haacked.com/archive/2008/03/13/url-routing-debugger.aspx/
Simply add it via NuGet, which will add a line to your appsettings, and then all your routes are displayed at the bottom of your page. Highly recommend for any routing issues.
只需通过 NuGet 添加它,它将在您的应用设置中添加一行,然后您的所有路由都会显示在您的页面底部。强烈建议解决任何路由问题。
In the end, my final version looks like:
最后,我的最终版本如下所示:
[RoutePrefix("Asset/AssetType")]
[Route("{action=index}/{id?}")]
[RoutePrefix("Asset/AssetType")]
[Route("{action=index}/{id?}")]

