使用ASP .Net核心(非mvc)的角度2路由
问题描述:
我试图设置使用.net核心和Angular 2的路由,但路由无法解析,因为它们由服务器解析。使用ASP .Net核心(非mvc)的角度2路由
我看到的一种解决方案是注册默认路由到您的家庭控制器或其他东西......但我没有任何MVC控制器。
我已经添加到了我的主要部件(和做其他所有的路由器的先决条件)
@RouteConfig([
{ path: '/', name: 'Table', component: TableComp, useAsDefault: true },
{ path: '/login', name: 'Login', component: LoginComp }
])
我做startup.cs有这些:
ConfigureServices()
内services.AddMvc();
内配置()
app.UseMvc();
但是因为我实际上没有使用任何MVC控制器或注册任何MVC路由,所以我不知道如何让我的角路由在浏览器而不是服务器中解析,以及为什么它们不仅仅是做的事...
答
下面的配置应适合使用客户端路由在.NET中最核心的项目:
DefaultFilesOptions options = new DefaultFilesOptions();
options.DefaultFileNames.Clear();
options.DefaultFileNames.Add("index.html");
app.Use(async (context, next) =>
{
await next();
if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
{
context.Request.Path = "/index.html";
await next();
}
})
.UseCors("AllowAll")
.UseMvc()
.UseDefaultFiles(options)
.UseStaticFiles();
答
您正在寻找在this GitHub库中发现的Microsoft.AspNetCore.SpaServices
。寻找这个example。
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new { controller = "Home", action = "Index" });
});
这里有一个older post这里有一些以前的版本,但设置应该非常相似。
答
试试这个example Asp Core + Angular2 + Swashbuckle + Docker。
它使用UseMvc()
用于C#API控制器。和UseStaticFiles()
服务AngularJs(和其他静态)文件。
因此,您将Asp Core后端作为服务运行。使用Webpack,您可以从Typescript源代码构建AngularJs应用程序。它将被发布到public
文件夹后端看起来服务于静态。
答
我把index.html放在wwwroot中,并在启动页面中使用DefaultFiles()。网络服务器知道并自动找到默认文件 - index.html。
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseMvc();
}
我建议使用单个MVC控制器来服务单个Index.cshtml视图。这使您可以利用内置在路由和标签助手中的asp.net。 –