【发布时间】:2013-06-01 10:47:18
【问题描述】:
我对 MVC 框架比较陌生,但我确实有一个功能正常的 Web 项目,它带有一个使用 AttributeRouting(NuGet 包)的 API 控制器 - 但是,我正在启动另一个项目,它只是不想遵循路线我到位了。
控制器:
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 not found 错误。如果我将路由更改为“/api/blazr/users” - 我会收到有关多个操作的错误,并且无法确定要执行的操作。
感谢您提供任何帮助 - 我真的只需要轻轻一推即可找出问题所在,无需为我完全解决它(我需要学习!)
谢谢
编辑
routes.axd:
api/{controller}/{id}
{resource}.axd/{*pathInfo}
{controller}/{action}/{id}
【问题讨论】:
-
当您使用来自
AttributeRouting的“路由调试器”(应该在~/routes.axd可用)时,您是否看到来自属性的预期路由,即/api/q/users? -
不,只是 api/{controller}/{id}、{resource}.axd/{*pathInfo} 和 {controller}/{action}/{id}。当我在 MapAttributeRoutes() 上中断应用程序时 - 路由集合返回 0 个路由...
-
我通过在我的控制器中实现 IController 让路由显示在 routes.axd 中 - 但它仍然不太正确(返回空白页面)
-
请告诉我们你是如何修复它的。
-
我更新了问题。问题是我有 MVC AttributeRouting NuGet,但需要 AttributeRouting 的 web api nuget
标签: c# asp.net-mvc asp.net-web-api attributerouting