index.html页面未加载。 asp.net核心中的角度2

时间:2016-10-07 07:14:52

标签: angular asp.net-core

我正在使用asp.net核心创建一个角度2应用程序。 index.html doents似乎在浏览器上加载。

以下是startup.cs中的代码。如果你注意到,我已经处理了404异常并告诉应用程序加载index.html。我在调试时看到的请求路径是/。最终我在浏览器上找到了404错误页面未找到的页面。我已经评论了MVC路由,因此角度路由优先。有人可以告诉我问题是什么。

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using Glimpse;
using System.IO;

namespace AspNetCoreAngularDemo1
{
    public class Startup
    {
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940

        public Startup(IHostingEnvironment env)
        {
            // Set up configuration sources.
            var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json")
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

            builder.AddEnvironmentVariables();
            Configuration = builder.Build();
        }

        public void ConfigureServices(IServiceCollection services)
        {
           // services.AddGlimpse();
            services.AddMvc();
        }


        public IConfigurationRoot Configuration { get; set; }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.Use(async (context, next) =>
            {
                await next();

                // If there's no available file and the request doesn't contain an extension, we're probably trying to access a page.
                // Rewrite request to use app root
                if (context.Response.StatusCode == 404 && !Path.HasExtension(context.Request.Path.Value))
                {
                    context.Request.Path = "/index.html"; // Put your Angular root page here 
                    context.Response.StatusCode = 200; // Make sure we update the status code, otherwise it returns 404
                    await next();
                }
            });

            // Serve wwwroot as root
            app.UseFileServer();

            // Serve /node_modules as a separate root (for packages that use other npm modules client side)
            app.UseFileServer(new FileServerOptions()
            {
                // Set root of file server
              //  FileProvider = new PhysicalFileProvider(Path.Combine(environment.ApplicationBasePath, "node_modules")),
                // Only react to requests that match this path
                RequestPath = "/node_modules",
                // Don't expose file system
                EnableDirectoryBrowsing = false
            });


            //app.UseMvc(routes =>
            //{
            //    //routes.MapRoute("default",
            //    //                "{controller=Home}/{action=Index}/{id?}");
            //    routes.MapRoute("spa-fallback",
            //                    "{*anything}",
            //                    new { controller = "Home", action = "Index" });
            //    //routes.MapWebApiRoute("defaultApi",
            //    //                      "api/{controller}/{id?}");
            //});




        }
    }
}

Application structure

app.component.ts

import { Component } from '@angular/core';
import { DataTable, Column } from 'primeng/primeng';
import { Router } from  '@angular/router';
import {  Routes, RouterModule } from  '@angular/router';
import { RiskListComponent } from './components/risks/risk-list.component';
import { RiskDetailsComponent } from './components/risks/risk-detail.component';
import { ModuleWithProviders } from '@angular/core';
import './rxjs-operators';


//import { RiskService } from './components/risks/risk.service';

@Component({
    selector: 'my-app',
    templateUrl : '../index.html'
    //template: `
    //<div>
    //    <h1>{{pageTitle}}</h1>
    //      <rm-risks> </rm-risks> 
    //</div>
    // <nav>
    //  <a routerLink="/dashboard" >Dashboard</a>
    //  <a routerLink="/risks" >Risks</a>

    //</nav>
    //<div>
    //  <router-outlet>  </router-outlet>
    //</div>
    // `
    //// <a routerLink="/riskdetails" routerLinkActive="active">RiskDetails</a>
    //< a routerLink="/welcome" routerLinkActive="active" > Welcome < /a>
    //,
    //directives: [RiskListComponent, DataTable, Column],

})

export class AppComponent {
    pageTitle: string = 'Test UK Trader';
}

app.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }   from '@angular/forms';
import { AppComponent }  from './app.component';
import { RiskListComponent } from './components/risks/risk-list.component';
import { RiskDetailsComponent } from './components/risks/risk-detail.component';
import { RiskService } from './components/risks/risk.service';

import {
    LocationStrategy,
    HashLocationStrategy
} from '@angular/common';

import { routing,
    appRoutingProviders}  from './app.routing';

@NgModule({
    imports: [BrowserModule, FormsModule, routing],
    declarations: [AppComponent, RiskListComponent, RiskDetailsComponent],
    providers: [
        appRoutingProviders, RiskService, { provide: LocationStrategy, useClass: HashLocationStrategy }
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }  

app.routing.ts

import { ModuleWithProviders } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { RiskListComponent } from './components/risks/risk-list.component';
import { RiskDetailsComponent } from './components/risks/risk-detail.component';
//import {DashboardComponent} from './components/Dashboard.component'
//import { WelcomeComponent } from  './components/home/welcome.component';

const appRoutes: Routes = [
    { path: '', pathMatch: 'full', component: RiskListComponent },
    { path: 'risks', component: RiskDetailsComponent },
    { path: 'risks/:id', component: RiskDetailsComponent },

];


export const appRoutingProviders: any[] = [

];

export const routing: ModuleWithProviders = RouterModule.forRoot(appRoutes);

main.ts

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { RiskService } from './components/risks/risk.service';
import { HttpModule, JsonpModule } from  '@angular/http';
import './rxjs-operators';
import { enableProdMode } from '@angular/core';
import { AppModule } from './app.module';


const platform = platformBrowserDynamic();

platform.bootstrapModule(AppModule, [HttpModule, JsonpModule, RiskService]).catch(err => console.error(err));

的index.html

<html>
<head>
    <title>Angular QuickStart</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="styles.css">
    <!-- 1. Load libraries -->
    <!-- Polyfill(s) for older browsers -->
    <script src="node_modules/core-js/client/shim.min.js"></script>
    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <!-- 2. Configure SystemJS -->
    <script src="systemjs.config.js"></script>
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
</head>
<!-- 3. Display the application -->
<body>
    <my-app>Loading...</my-app>
</body>
</html>

0 个答案:

没有答案