我有一个 Web API 2 API Controller
[RoutePrefix("things")]
public class ThingsController : APIController
{
[Route("{thingId}", Name="Things.Get")]
public Thing Get(string thingId)
{
//snip...
}
}
一切都很好...除了我想将该路由的 URL 传递给一些 JS,以便它可以构建 URL 来请求 Things
所以在 Razor View 中我已经尝试过
myJavascriptObject.thingUrl = '@Url.Action("Get", "Things", new {area=""})';
但是我得到一个空字符串
我试过给 Controller 路由一个明确的名称并使用
@Url.RouteUrl("Things.Get", new {areas="", thingId="foo"}")
b
但那也是一个空字符串。
我是不是傻了?这应该有效吗?
经过更多尝试后更新。
在 MVC Controller 上(我需要知道 API Controller 路由)
var something = Url.Action("Get", "Things", new {area = ""});
var somethingWithId = Url.Action("Get", "Things", new { area = "", siteId = "fakeId" });
var somethingElse = Url.RouteUrl(new {Action = "Get", Controller = "Things", Area = ""});
var somethingElseWithId = Url.RouteUrl(new { Action = "Get", Controller = "Things", Area = "", siteId = "fakeId" });
这些都是空的。
如果我删除 area=""
条件,那么我会得到一条路线,但其中有区域名称,而 route 没有区域名称。
?!
最佳答案
TL;DR - 如果有什么东西很奇怪,请在新环境中将其钉住
在非常遥远的情况下在这里留下答案可以帮助其他人。
正如有人向我指出这对他们有用,我创建了一个新的 MVC 和 API 项目并查看了默认路由。
我们的看起来像这样:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "home",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new [] { "Another.Project.Controllers" }
);
}
什么?
我将其替换为默认路由配置:
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 }
);
}
其他一切仍然有效并且我可以获得我想要的路线。
我们绝对没有在该项目中使用其他 namespace ,我猜测 namespace 是在该解决方案是另一个解决方案(它曾经是)的一部分时引入的,或者是通过移动它的重构引入的。
因此,对于任何非常恼人的错误,我都会自然而然地得出结论:“这到底是怎么回事?!”
关于c# - 在 Razor View 中的 ASP.NET WEB API 中获取路由前缀的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29029818/