我对MVC框架比较新,但我已经有一个使用AttributeRouting(NuGet包)的API控制器的Web项目-然而,我正在开始另一个项目,它就是不想按照我设定的路由走。
控制器:
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
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:
// 注意:如需启用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);
}
}
当我试图导航到 /api/q/users 时,我收到了一个 404 找不到错误。如果我更改路由为 "/api/blazr/users",我会收到有关多个操作和无法确定要执行哪个操作的错误。欢迎任何帮助 - 我只需要一个小推动就能找出问题所在,不需要完全解决它(我需要学习!)
谢谢
编辑
routes.axd:
api/{controller}/{id}
{resource}.axd/{*pathInfo}
{controller}/{action}/{id}
AttributeRouting
中的“路由调试器”(应该在~/routes.axd
处可用)时,是否可以看到来自属性的预期路由,例如/api/q/users
? - David Tansey