Angular 2测试版默认使用html5路由。但是,当您转到一个组件,并且路由发生更改(例如http://localhost:5000/aboutus)并重新加载/刷新页面时,将不会加载任何内容。
该问题也在此中提出。大多数答案说,如果我们要在angular 2中实现HTML5路由,那么这个路由问题应该在服务器端解决。更多讨论。
我不确定如何使用asp.net服务器环境来处理这个问题。
有没有使用asp.net的angular 2开发者也遇到过这个问题?
PS。我使用的是MVC5,我的Angular 2路由使用的是ASP.NET路由。
发布于 2016-03-17 03:16:25
您看到的问题与客户端的Angular路由和MVC服务器端路由之间的差异有关。您实际上收到了一个404 Page Not Found
错误,因为服务器没有该路由的控制器和操作。我怀疑你没有处理错误,这就是为什么它看起来好像什么都没有发生。
当您重新加载http://localhost:5000/aboutus
时,或者如果您试图通过快捷方式直接链接到该网址,或者通过在地址栏中键入该网址(深度链接),它会向服务器发送一个请求。ASP.NET MVC将尝试解析该路由,在您的示例中,它将尝试加载aboutusController
并运行Index
操作。当然,这不是您想要的,因为您的aboutus
路由是一个角度组件。
您应该做的是为Angular MVC路由器创建一种方法,以便将应由ASP.NET解析的URL传递回客户端。
在您的Startup.cs
文件的Configure()
方法中,向现有路由添加一个"spa-fallback“路由:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
// when the user types in a link handled by client side routing to the address bar
// or refreshes the page, that triggers the server routing. The server should pass
// that onto the client, so Angular can handle the route
routes.MapRoute(
name: "spa-fallback",
template: "{*url}",
defaults: new { controller = "Home", action = "Index" }
);
});
通过创建一个指向最终加载您的Angular应用程序的Controller和View的通用路由,这将允许将服务器未处理的URL传递到客户端以进行正确的路由。
发布于 2016-06-10 14:42:34
在您的Startup.cs
中,将此代码添加到Configure
方法。这必须在其他app
语句之前。
app.Use(async (context, next) => {
await next();
if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value)) {
context.Request.Path = "/index.html"; // Put your Angular root page here
await next();
}
});
发布于 2016-08-05 07:51:47
我最喜欢的解决方案是将以下代码添加到Global.asax.cs中,它可以非常流畅和可靠地解决这个问题:
private const string RootUrl = "~/Home/Index";
// You can replace "~Home/Index" with whatever holds your app selector (<my-app></my-app>)
// such as RootUrl="index.html" or any controller action or browsable route
protected void Application_BeginRequest(Object sender, EventArgs e)
{
// Gets incoming request path
var path = Request.Url.AbsolutePath;
// To allow access to api via url during testing (if you're using api controllers) - you may want to remove this in production unless you wish to grant direct access to api calls from client...
var isApi = path.StartsWith("/api", StringComparison.InvariantCultureIgnoreCase);
// To allow access to my .net MVCController for login
var isAccount = path.StartsWith("/account", StringComparison.InvariantCultureIgnoreCase);
if (isApi || isAccount)
{
return;
}
// Redirects to the RootUrl you specified above if the server can't find anything else
if (!System.IO.File.Exists(Context.Server.MapPath(path)))
Context.RewritePath(RootUrl);
}
https://stackoverflow.com/questions/34628536
复制相似问题