部署到 IIS 的 Angular 6 .net core 2.1.1 应用程序中出现 500 错误

亚历克斯

我已将我的项目从旧的 Visual Studio SPA Angular 模板转换为最新的。我还将项目从 Angular 5 转换为 Angular 6,并从 webpack 转换为 angular-cli。后端运行.Net Core 2.1.1。

这一切在开发中都很好用,但在部署到 IIS 时出现 500 错误。最新的托管包安装在 IIS 中并且运行正常。我可以部署旧版本的应用程序,它运行良好,但新版本拒绝合作。

我也没有看到日志文件来尝试追踪它。

有什么想法吗?

这是我的 angular.json

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "ClientApp": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {
        "@schematics/angular:component": {
          "styleext": "scss"
        }
      },
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/ClientApp",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.app.json",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "node_modules/font-awesome/css/font-awesome.min.css",
              "node_modules/primeng/resources/primeng.min.css",
              "node_modules/primeicons/primeicons.css",
              "node_modules/videogular2/fonts/videogular.css",
              "src/assets/theme/theme-blue.scss",
              "src/styles.scss"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "ClientApp:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "ClientApp:build:production"
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "ClientApp:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "src/tsconfig.spec.json",
            "karmaConfig": "src/karma.conf.js",
            "styles": [
              "src/styles.scss"
            ],
            "scripts": [],
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ]
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": [
              "src/tsconfig.app.json",
              "src/tsconfig.spec.json"
            ],
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    },
    "ClientApp-e2e": {
      "root": "e2e/",
      "projectType": "application",
      "architect": {
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "ClientApp:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "ClientApp:serve:production"
            }
          }
        },
        "lint": {
          "builder": "@angular-devkit/build-angular:tslint",
          "options": {
            "tsConfig": "e2e/tsconfig.e2e.json",
            "exclude": [
              "**/node_modules/**"
            ]
          }
        }
      }
    }
  },
  "defaultProject": "ClientApp"
}

这是我的startup.cs

using Driver.Server.DBContext;
using Driver.Server.Repositories;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SpaServices.AngularCli;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using AutoMapper;
using Driver.Server.Models.Entities;
using System;
using Microsoft.AspNetCore.Identity;
using System.Net;
using Microsoft.AspNetCore.Diagnostics;
using Driver.Server.Helpers;
using Microsoft.AspNetCore.Http;
using Driver.Server.Auth;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.IdentityModel.Tokens;
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Driver.Server.Services;
using Microsoft.AspNetCore.Antiforgery;
using Driver.Server.Models;
using Microsoft.Extensions.Logging;
using Driver.Server.Repositories.Interfaces;

namespace Driver {
    public class Startup {

        private readonly IConfiguration _config;

        public Startup(IConfiguration config) {
            _config = config;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services) {

            services.AddDbContext<DriverDbContext>(options => options.UseSqlServer(_config.GetConnectionString("DriverDBConnection")));

            services.AddSingleton<IJwtFactory, JwtFactory>();

            services.TryAddTransient<IHttpContextAccessor, HttpContextAccessor>();

            services.AddIdentity<AppUser, AppRole>()
                .AddEntityFrameworkStores<DriverDbContext>()
                .AddDefaultTokenProviders();

            var settings = _config.GetSection("AuthenticationSettings").Get<AuthenticationSettings>();


            services.AddScoped<IMailService, MailService>();


            var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(settings.SecretKey));

            // Configure JwtIssuerOptions
            services.Configure<JwtIssuerOptions>(options => {
                options.Issuer = settings.JwtIssuerOpts.Issuer;
                options.Audience = settings.JwtIssuerOpts.Audience;
                options.SigningCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            });

            // Specify the validation parameters to dictate how we want received tokens validated
            var tokenValidationParameters = new TokenValidationParameters {
                ValidateIssuer = true,
                ValidIssuer = settings.JwtIssuerOpts.Issuer,

                ValidateAudience = true,
                ValidAudience = settings.JwtIssuerOpts.Audience,

                ValidateIssuerSigningKey = true,
                IssuerSigningKey = signingKey,

                RequireExpirationTime = false,
                ValidateLifetime = true,
                ClockSkew = TimeSpan.Zero
            };


            services.AddAuthentication(options => {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

            }).AddJwtBearer(options => {
                options.ClaimsIssuer = settings.JwtIssuerOpts.Issuer;
                options.TokenValidationParameters = tokenValidationParameters;
                options.SaveToken = true;
            });

            // Create an authorization claim policy to guard API controllers and actions
            services.AddAuthorization(options => {
                options.AddPolicy(
                    Constants.PolicyNames.ApiUser,
                    policy => policy.RequireClaim(
                        Constants.JwtClaimIdentifiers.Rol,
                        Constants.Claims.ApiAccess));
            });

            services.Configure<IdentityOptions>(options => {
                // Password settings
                options.Password.RequireDigit = settings.PasswordSettings.RequiredDigit;
                options.Password.RequiredLength = settings.PasswordSettings.RequiredLength;
                options.Password.RequireNonAlphanumeric = settings.PasswordSettings.RequireNonAlphanumeric;
                options.Password.RequireUppercase = settings.PasswordSettings.RequireUppercase;
                options.Password.RequireLowercase = settings.PasswordSettings.RequireLowercase;
                options.Password.RequiredUniqueChars = settings.PasswordSettings.RequiredUniqueChars;

                // Lockout settings
                options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(settings.LockoutSettings.DefaultLockoutTimeSpan);
                options.Lockout.MaxFailedAccessAttempts = settings.LockoutSettings.MaxFailedAccessAttempts;
                options.Lockout.AllowedForNewUsers = settings.LockoutSettings.AllowedForNewUsers;

                // User settings
                options.User.RequireUniqueEmail = settings.UserSettings.RequireUniqueEmail;
            });

            services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration => {
                configuration.RootPath = "ClientApp/dist";
            });

            services.AddAutoMapper(typeof(Startup));

            services.AddSingleton(_config);

            services.AddScoped<ICompanyRepository, CompanyRepository>();
            services.AddScoped<ILookupRepository, LookupRepository>();
            services.AddScoped<IManagerRepository, ManagerRepository>();
            services.AddScoped<IAppUserRepository, AppUserRepository>();
            services.AddScoped<IAppRoleRepository, AppRoleRepository>();
            services.AddScoped<IRefreshTokenRepository, RefreshTokenRepository>();
            services.AddScoped<ILoginAttemptRepository, LoginAttemptRepository>();
            services.AddScoped<INavigationTraceRepository, NavigationTraceRepository>();
            services.AddScoped<IVideoRepository, VideoRepository>();
            services.AddScoped<IJobRequisitionRepository, JobRequisitionRepository>();
            services.AddScoped<IJobOrderRepository, JobOrderRepository>();
            services.AddScoped<IMailService, MailService>();
            services.AddScoped<IEmailLogRepository, EmailLogRepository>();
            services.AddScoped<ITrackingRepository, TrackingRepository>();

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(
            IApplicationBuilder app,
            IHostingEnvironment env,
            IAntiforgery antiforgery) {
            if (env.IsDevelopment()) {
                app.UseDeveloperExceptionPage();
            }
            else {
                app.UseHsts();
            }

            app.UseExceptionHandler(
                builder => {
                    builder.Run(
                        async context => {
                            context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                            context.Response.Headers.Add("Access-Control-Allow-Origin", "*");

                            var ex = context.Features.Get<IExceptionHandlerFeature>();
                            if (ex != null) {
                                var message = string.Join(
                                    Environment.NewLine,
                                    "MESSAGE:",
                                    ex.Error.Message,
                                    ex.Error.InnerException != null ? "INNER EXCEPTION MESSAGE:" + Environment.NewLine + ex.Error.InnerException.Message : ""
                                    );
                                context.Response.AddApplicationError(ex.Error.Message);

                                await context.Response.WriteAsync(message).ConfigureAwait(false);
                            }
                        });
                });

            //Todo: Turn on Authentication
            app.UseAuthentication();
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSpaStaticFiles();

            //If request is first entry point to server (not an api call)
            //Generate the anti-forgery cookies
            app.Use(async (context, next) => {

                string path = context.Request.Path.Value;

                if (path != null && !path.Contains("/api", StringComparison.OrdinalIgnoreCase)) {
                    // XSRF-TOKEN used by angular in the $http if provided
                    context.Response.Cookies.Append(
                        "XSRF-TOKEN",
                        antiforgery.GetAndStoreTokens(context).RequestToken,
                        new CookieOptions { HttpOnly = false, Secure = true }
                        );
                }

                await next();
            });

            app.UseMvc(routes => {
                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action=Index}/{id?}");

            });

            app.UseSpa(spa => {
                // To learn more about options for serving an Angular SPA from ASP.NET Core,
                // see https://go.microsoft.com/fwlink/?linkid=864501

                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment()) {
                    spa.UseAngularCliServer(npmScript: "start");
                }
            });
        }
    }
}

这是我的 web.config

<?xml version="1.0" encoding="utf-8"?>
    <configuration>
        <system.webServer>
            <security>
                <requestFiltering>
                <requestLimits maxAllowedContentLength="209715200" />
                </requestFiltering>
            </security>
            <rewrite>
                <rules>
                    <rule name="HTTP/S to HTTPS Redirect" enabled="true" stopProcessing="true">
                    <match url="(.*)" />
                    <conditions logicalGrouping="MatchAny">
                    <add input="{SERVER_PORT_SECURE}" pattern="^0$" />
                    </conditions>
                    <action type="Redirect" url="https://{HTTP_HOST}{REQUEST_URI}" redirectType="Permanent" />
                </rule>
                </rules>
            </rewrite>
            <modules runAllManagedModulesForAllRequests="false">
                <remove name="WebDAVModule" />
            </modules>
            <handlers>
                <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
            </handlers>
            <aspNetCore processPath="dotnet" arguments=".\Driver.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
        </system.webServer>
    </configuration>
<!--ProjectGuid: 3bb90a77-cfdb-4435-bad5-3895ee14f1d3-->
亚历克斯

发现问题了。angular.json 中的 outputpath 属性设置为:

"outputPath": "dist/ClientApp"

什么时候应该是:

“输出路径”:“分布”

这导致在 clientapp/dist/clientapp 而不是 clientapp/dist 中生成所有角度文件

我通过在 web.config 中打开页面日志来找到它。日志文件显示没有找到 index.html 文件,这让我去查看生成角度文件的位置。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

将ASP.NET Core API部署到本地IIS错误500

来自分类Dev

将asp.net核心Web API部署到IIS 7.5时出现500错误

来自分类Dev

在 IIS-10 上部署平面 angular-2 应用程序(无 asp.net core)

来自分类Dev

在IIS中部署.NET Core RC2时出现服务器错误502

来自分类Dev

ASP.Net Core反应将其作为应用程序部署到IIS

来自分类Dev

将ASP.NET 5 MVC 6应用程序部署到Linux和IIS 7

来自分类Dev

IIS永远启动Asp.Net Core RC1应用程序

来自分类Dev

使用Entity Framework将Web api部署到Azure,工作1小时,现在出现错误500

来自分类Dev

无法将ASP.NET Core 2.1 Angular应用程序部署到Azure

来自分类Dev

将Flask应用程序部署到heroku会导致create_app()出现500错误

来自分类Dev

发布发布在IIS中的blazor程序集应用程序ASP.NET CORE后,出现DirectoryNotFoundException错误

来自分类Dev

是否可以将ASP.NET MVC 5应用程序部署到Windows Server 2003 IIS 6

来自分类Dev

“自定义错误”页面.Net Core Web应用程序未显示500错误

来自分类Dev

在Azure上部署Angular2应用程序时出现节点版本错误

来自分类Dev

ASP.NET Core 1 RC2 Web应用程序入口点

来自分类Dev

将WebAPI发布到IIS上的角度应用程序的api文件夹后,根据请求会出现500个错误。

来自分类Dev

将 Flask 应用程序部署到 AWS beanstalk 时出现错误 [Errno 2]

来自分类Dev

Angular 6 - 将 Angular 6 部署到 Github Pages 错误

来自分类Dev

如何获得在服务器上使用的正确的appsettings.json-将.NET Core应用程序部署到Windows Server上的IIS?

来自分类Dev

.net core 2.1 Web 应用程序可在 Visual Studio 中运行,但在 Windows 10 中部署到 IIS 时不起作用

来自分类Dev

IIS 7.5中的ASP.NET Core WebAPI 500内部错误

来自分类Dev

使用“服务器响应非Javascript MIME类型“ text / html”?”在本地将Angular 8应用程序部署到IIS错误。

来自分类Dev

将Angular 2应用程序部署到Azure

来自分类Dev

将 Angular 2 应用程序部署到 Azure

来自分类Dev

在.Net Core-hub上的IIS中的IIS中运行Signalr,但客户端看到500错误

来自分类Dev

在Service Fabric中调试.NET Core RC2 Web应用程序时出现错误消息

来自分类Dev

在Service Fabric中调试.NET Core RC2 Web应用程序时出现错误消息

来自分类Dev

Javascript,从1到500,而不是1和2

来自分类Dev

在CodePipeline中部署的Laravel Elastic Beanstalk应用程序出现500个服务器错误

Related 相关文章

  1. 1

    将ASP.NET Core API部署到本地IIS错误500

  2. 2

    将asp.net核心Web API部署到IIS 7.5时出现500错误

  3. 3

    在 IIS-10 上部署平面 angular-2 应用程序(无 asp.net core)

  4. 4

    在IIS中部署.NET Core RC2时出现服务器错误502

  5. 5

    ASP.Net Core反应将其作为应用程序部署到IIS

  6. 6

    将ASP.NET 5 MVC 6应用程序部署到Linux和IIS 7

  7. 7

    IIS永远启动Asp.Net Core RC1应用程序

  8. 8

    使用Entity Framework将Web api部署到Azure,工作1小时,现在出现错误500

  9. 9

    无法将ASP.NET Core 2.1 Angular应用程序部署到Azure

  10. 10

    将Flask应用程序部署到heroku会导致create_app()出现500错误

  11. 11

    发布发布在IIS中的blazor程序集应用程序ASP.NET CORE后,出现DirectoryNotFoundException错误

  12. 12

    是否可以将ASP.NET MVC 5应用程序部署到Windows Server 2003 IIS 6

  13. 13

    “自定义错误”页面.Net Core Web应用程序未显示500错误

  14. 14

    在Azure上部署Angular2应用程序时出现节点版本错误

  15. 15

    ASP.NET Core 1 RC2 Web应用程序入口点

  16. 16

    将WebAPI发布到IIS上的角度应用程序的api文件夹后,根据请求会出现500个错误。

  17. 17

    将 Flask 应用程序部署到 AWS beanstalk 时出现错误 [Errno 2]

  18. 18

    Angular 6 - 将 Angular 6 部署到 Github Pages 错误

  19. 19

    如何获得在服务器上使用的正确的appsettings.json-将.NET Core应用程序部署到Windows Server上的IIS?

  20. 20

    .net core 2.1 Web 应用程序可在 Visual Studio 中运行,但在 Windows 10 中部署到 IIS 时不起作用

  21. 21

    IIS 7.5中的ASP.NET Core WebAPI 500内部错误

  22. 22

    使用“服务器响应非Javascript MIME类型“ text / html”?”在本地将Angular 8应用程序部署到IIS错误。

  23. 23

    将Angular 2应用程序部署到Azure

  24. 24

    将 Angular 2 应用程序部署到 Azure

  25. 25

    在.Net Core-hub上的IIS中的IIS中运行Signalr,但客户端看到500错误

  26. 26

    在Service Fabric中调试.NET Core RC2 Web应用程序时出现错误消息

  27. 27

    在Service Fabric中调试.NET Core RC2 Web应用程序时出现错误消息

  28. 28

    Javascript,从1到500,而不是1和2

  29. 29

    在CodePipeline中部署的Laravel Elastic Beanstalk应用程序出现500个服务器错误

热门标签

归档