. Net сайт core 3 с 404 ошибками - PullRequest
0 голосов
/ 21 февраля 2020

У меня есть сайт. Net core 3, который я пытаюсь разместить. Я уже успешно развернул один сайт и пытаюсь развернуть второй сайт, но мне не повезло. Если я указываю папку рабочего сайта на папку новых сайтов, а также разделяю пул приложений рабочего сайта, он работает, поэтому я на 100% уверен, что это проблема конфигурации IIS. Я получаю 404 ошибки при попытке просмотреть. Единственное отличие для нового сайта в том, что он находится на другом порту, и сертификат не установлен, поэтому, возможно, SSL-код в моем запуске дает эффект

public class Startup
{

    private string path = string.Empty;
    private string connection = string.Empty;

    public class ErrorDetails
    {
        public int StatusCode { get; set; }
        public string Message { get; set; }
        public override string ToString()
        {
            return JsonConvert.SerializeObject(this);
        }
    }

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    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.AddHttpsRedirection(options =>
        {
            options.RedirectStatusCode = StatusCodes.Status308PermanentRedirect;
            options.HttpsPort = 443;
        });

        //services.AddResponseCaching();
        services.AddMvc(option => option.EnableEndpointRouting = false).AddJsonOptions(options => {
            options.JsonSerializerOptions.IgnoreNullValues = true;

        });

        services.AddControllersWithViews();

        services.AddHttpContextAccessor();

        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(options => {
                    options.LoginPath = "/Account/Login/";
                    options.AccessDeniedPath = "/Account/Denied";
                    //options.Cookie.IsEssential = true;
                }); 
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseRouting();

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

        //app.UseResponseCaching();

        app.UseMvc();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapDefaultControllerRoute();

            //endpoints.MapControllerRoute(
            //    name: "default",
            //    pattern: "{controller=Home}/{action=Index}/{id?}");
        });

        app.UseExceptionHandler(appError =>
        {
            appError.Run(async context =>
            {
                context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                context.Response.ContentType = "application/json";

                var contextFeature = context.Features.Get<IExceptionHandlerFeature>();

                var exceptionFeature = context.Features.Get<IExceptionHandlerPathFeature>();

                if (exceptionFeature != null)
                {
                    // Get which route the exception occurred at
                    string routeWhereExceptionOccurred = exceptionFeature.Path;

                    // Get the exception that occurred
                    Exception exceptionThatOccurred = exceptionFeature.Error;

                    Serilog.Log.Error($" Web API error in controller:{routeWhereExceptionOccurred}" + Environment.NewLine + exceptionThatOccurred.ToString() + Environment.NewLine + new String('-', 100));

                    await context.Response.WriteAsync(new ErrorDetails()
                    {
                        StatusCode = context.Response.StatusCode,
                        Message = $"Unhandled exception at location:{routeWhereExceptionOccurred}, please see log files located in:{path} for details" + Environment.NewLine + Environment.NewLine + "Exception:" + exceptionThatOccurred.ToString()

                    }.ToString());
                }

            });
        });
    }
}

1 Ответ

0 голосов
/ 24 февраля 2020

Насколько я знаю, метод services.AddHttpsRedirection заставит запрос http перенаправить на https.

Но если вы не привязываете https на сервере IIS, это означает, что URL-адрес https отсутствует , поэтому он вернет ошибку 404.

Чтобы решить эту проблему, я предлагаю вам удалить этот метод, если вы не хотите включать https для веб-приложения.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...