【发布时间】:2013-11-07 17:01:53
【问题描述】:
我一直在使用 Web API 在 ASP.NET MVC 内部开发一个 AngularJS 项目。除非您尝试直接转到有角度的路由 URL 或刷新页面,否则它工作得很好。我认为我可以使用 MVC 的路由引擎来处理这件事,而不是胡闹服务器配置。
当前的 WebAPIConfig:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { id = @"^[0-9]+$" }
);
config.Routes.MapHttpRoute(
name: "ApiWithActionAndName",
routeTemplate: "api/{controller}/{action}/{name}",
defaults: null,
constraints: new { name = @"^[a-z]+$" }
);
config.Routes.MapHttpRoute(
name: "ApiWithAction",
routeTemplate: "api/{controller}/{action}",
defaults: new { action = "Get" }
);
}
}
当前路由配置:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute(""); //Allow index.html to load
routes.IgnoreRoute("partials/*");
routes.IgnoreRoute("assets/*");
}
}
当前 Global.asax.cs:
public class WebApiApplication : HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
var formatters = GlobalConfiguration.Configuration.Formatters;
formatters.Remove(formatters.XmlFormatter);
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
PreserveReferencesHandling = PreserveReferencesHandling.None,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
};
}
}
目标:
/api/* 继续转到 WebAPI,/partials/ 和 /assets/ 都转到文件系统,绝对其他任何东西都被路由到 /index.html,这是我的 Angular 单曲页面应用程序。
--编辑--
我似乎已经让它工作了。将此添加到 BOTTOM OF RouteConfig.cs:
routes.MapPageRoute("Default", "{*anything}", "~/index.html");
而对根 web.config 的更改:
<system.web>
...
<compilation debug="true" targetFramework="4.5.1">
<buildProviders>
...
<add extension=".html" type="System.Web.Compilation.PageBuildProvider" /> <!-- Allows for routing everything to ~/index.html -->
...
</buildProviders>
</compilation>
...
</system.web>
但是,它闻起来像黑客。有更好的方法吗?
【问题讨论】:
-
作为对那些尝试的人(并且对于他们下面的答案并不理想)的说明,这个问题中列出的黑客有效,但如果用户输入的路径也恰好是一个文件夹,则不是。因此,例如,如果您将所有内容路由到
~/index.html,那么只有在您的应用程序中没有名为/whatever/的文件夹路径时,路径/whatever/才会路由到那里。 -
任何想法如何解决这个警告?
-
感谢一个不得不将 Angular 塞进旧版 MVC 应用程序的人
标签: c# asp.net asp.net-mvc asp.net-mvc-4 angularjs