簡體   English   中英

使用 wwwroot 作為 Angular 項目文件的路徑在 Kestrel 服務器上運行的 ASP.Net API 項目無法獲取 Angular

[英]Can't get Angular with ASP.Net API project running on Kestrel server using wwwroot as path to Angular project files

信息- 我正在 VS Code 中成功運行和調試我的(Angular 10 / ASP.Net 5)站點,使用 >ng serve 和 >dotnet run 連接到 localhost:4200,我現在想將它發布到 Azure,但首先我想要僅在 Kestrel 上進行本地測試,方法是將 Angular 項目構建到 .Net API 項目中的 wwwroot 文件夾並從 localhost:5001 運行該站點。 我在我的 API 項目文件夾中構建(>ng build)到 wwwroot,我看到所有 Angular 文件都在 wwwroot 文件夾中創建,然后我執行 >dotnet run。

我懂了

現在收聽:https://localhost:5001

然后我打開瀏覽器點擊 url 我在終端看到這些錯誤

信息:Microsoft.AspNetCore.Hosting.Diagnostics[1] 請求開始 HTTP/1.1 GET https://localhost:5001/ - - 信息:Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2] 授權失敗。 未滿足這些要求: DenyAnonymousAuthorizationRequirement:需要經過身份驗證的用戶。 信息:Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[12] AuthenticationScheme:承載被挑戰。 信息:Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2] 授權失敗。 未滿足這些要求: DenyAnonymousAuthorizationRequirement:需要經過身份驗證的用戶。 信息:Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[12] AuthenticationScheme:承載被挑戰。 信息:Microsoft.AspNetCore.Hosting.Diagnostics[2] 請求完成 HTTP/1.1 GET https://localhost:5001/ - - - 401 0 - 70.3847ms

問題- 這是配置問題嗎? CORS/權限問題? 身份驗證問題? 文件夾/路徑問題?

這是附加代碼,可幫助任何可能幫助我了解正在發生的事情的人

啟動.cs

配置服務()

public void ConfigureServices(IServiceCollection services)
    {
        services.AddAutoMapper(typeof(MappingEvents));
        services.AddAutoMapper(typeof(MappingMembers));
        services.AddAutoMapper(typeof(MappingUsers));
        services.AddAutoMapper(typeof(MappingYogabands));
        services.AddAutoMapper(typeof(MappingReviews));
        // services.AddControllers();
        services.AddControllers()
            .AddNewtonsoftJson(opt => 
            {
                opt.SerializerSettings.ReferenceLoopHandling =
                     Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            });


        services.AddDbContext<DataContext>(x =>
            x.UseSqlServer(_config.GetConnectionString("SqlServerConnection"), y => y.UseNetTopologySuite()));

        services.AddTransient<IEmailSender, EmailSender>();
        services.Configure<AuthMessageSenderOptions>(_config.GetSection("SendGrid"));
        services.Configure<ConfirmationOptions>(_config.GetSection("Confirmation"));

        services.Configure<CloudinarySettings>(_config.GetSection("CloudinarySettings"));
        
        services.AddApplicationServices();
        services.AddIdentityServices(_config);
        services.AddSwaggerDocumentation();


        // telling out client app, that if it's running on an unsecure port, we won't return a header, 
        // that will allow our browser to display that information
        // * only allowed to access info from localhost:4200, all others will be denied?
        services.AddCors(opt => 
        {
            opt.AddPolicy("CorsPolicy", policy => 
            {
                policy.AllowAnyHeader().AllowAnyMethod().WithOrigins("https://localhost:4200");
            });
        });
    }

配置()

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseMiddleware<ExceptionMiddleware>();

        // when coming into the server and we don't have an endpoint that matches the request, then we hit this below
        // it will then re direct to our error controller, pass in the status code and return an object result
        app.UseStatusCodePagesWithReExecute("/errors/{0}"); // after creating ErrorController

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseCors("CorsPolicy");

        app.UseAuthentication();
        app.UseAuthorization();

        app.UseSwaggerDocumention();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers().RequireAuthorization();
            // endpoints.MapControllers();
            endpoints.MapFallbackToController("Index", "Fallback");
        });
    }

AddIdentityService()(在 ConfigureServices() 中調用)

public static IServiceCollection AddIdentityServices(this IServiceCollection services, IConfiguration config)
    {
        services.Configure<IdentityOptions>(options =>
        {
            options.User.RequireUniqueEmail = true;
            options.User.AllowedUserNameCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@";
        });

        var builder = services.AddIdentityCore<User>(opt =>
        {
            opt.Password.RequireDigit = false;
            opt.Password.RequiredLength = 2;
            opt.Password.RequireNonAlphanumeric = false;
            opt.Password.RequireUppercase = false;
            // *******************************************************
            // for email confirmation
            opt.SignIn.RequireConfirmedEmail = true;
            // *******************************************************
        });

        builder = new IdentityBuilder(builder.UserType, typeof(Role), builder.Services);
        // AddDefaultTokenProviders() allows the ability to create a token to send to user when they forgot password
        builder.AddEntityFrameworkStores<DataContext>().AddDefaultTokenProviders();
        
        // for roles
        builder.AddRoleValidator<RoleValidator<Role>>();
        builder.AddRoleManager<RoleManager<Role>>();

        builder.AddSignInManager<SignInManager<User>>();

        services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options => 
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["Token:Key"])),
                    ValidIssuer = config["Token:Issuer"],
                    ValidateIssuer = true,
                    ValidateAudience = false
                };
            });

        services.AddAuthorization(options =>
        {
            options.AddPolicy("RequireAdminRole", policy => policy.RequireRole("Admin"));
            options.AddPolicy("ModeratePhotoRole", policy => policy.RequireRole("Admin", "Moderator"));
            options.AddPolicy("VipOnly", policy => policy.RequireRole("VIP"));
        });

        return services;
    }

Angular.json 文件的構建部分

"build": {
      "builder": "@angular-devkit/build-angular:browser",
      "options": {
        "allowedCommonJsDependencies": ["angular2-wizard", "hammerjs"],
        "outputPath": "../API/wwwroot",
        "index": "src/index.html",
        "main": "src/main.ts",
        "polyfills": "src/polyfills.ts",
        "tsConfig": "tsconfig.app.json",
        "aot": true,
        "assets": [
          "src/favicon.ico",
          "src/assets"
        ],
        "styles": [
          "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,
          "extractLicenses": true,
          "vendorChunk": false,
          "buildOptimizer": true,
          "budgets": [
            {
              "type": "initial",
              "maximumWarning": "2mb",
              "maximumError": "5mb"
            },
            {
              "type": "anyComponentStyle",
              "maximumWarning": "6kb",
              "maximumError": "10kb"
            }
          ]
        }
      }
    }

我的 Angular 項目中的 Environment.ts

 export const environment = { production: false, apiUrl: 'https://localhost:5001/api/' };

我解決了我的問題。 這就是我所做的。

  1. 將此行添加到 Startup.cs 中的 Configure()

    app.UseStaticFiles();

  2. 已移除

    .RequireAuthorization() 來自

    endpoints.MapControllers().RequireAuthorization();

現在它工作正常,在我的 API 項目中從 wwwroot 運行我的 Ng 應用程序

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM