2016-07-22 68 views
1

我試圖設置使用.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路由,所以我不知道如何讓我的角路由在瀏覽器而不是服務器中解析,以及爲什麼它們不僅僅是做的事...

+0

我建議使用單個MVC控制器來服務單個Index.cshtml視圖。這使您可以利用內置在路由和標籤助手中的asp.net。 –

回答

10

下面的配置應適合使用客戶端路由在.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(); 
+0

這會被添加到RouteConfig什麼的?或者我會添加什麼文件? – Brett

+0

經過測試和工作。這也適用於沒有UseCors和UseMvc。 – Gyocol

+0

@Brett這應該在de Startup中添加.Configure方法變量app是IApplicationBuilder – Gyocol

1

您正在尋找在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這裏有一些以前的版本,但設置應該非常相似。

0

試試這個example Asp Core + Angular2 + Swashbuckle + Docker。

它使用UseMvc()用於C#API控制器。和UseStaticFiles()服務AngularJs(和其他靜態)文件。

因此,您將Asp Core後端作爲服務運行。使用Webpack,您可以從Typescript源代碼構建AngularJs應用程序。它將被髮布到public文件夾後端看起來服務於靜態。

0

我把index.html放在wwwroot中,並在啓動頁面中使用DefaultFiles()。網絡服務器知道並自動找到默認文件 - index.html。

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
    { 

     app.UseDefaultFiles(); 
     app.UseStaticFiles(); 

     app.UseMvc(); 
    }