Как добавить мою собственную аутентификацию с помощью файлов cookie в ASP.Net Core Razor? - PullRequest
0 голосов
/ 28 ноября 2018

ich verzweifle mittlerweile schon seit fast einer Woche.Их можно найти на веб-сайте C # und habe mich be Erstellung des Projektes gegen ein MVC-Modell entschieden (Weil ich das nicht so ganz verstehe…).Это также и веб-сайт eEnfache (Visual Studio 2017), а также веб-сайт.Ich habe Klassen wie in normalen WPF Anwendungen und komme bis jetzt ganz gut damit zurecht.Основная проблема: Ich schaffe es einfach nicht Cookie- bzw.Сессия-Variablen ZU Speichern.Cookies kann ich schon auslesen, ebenso, wie fast alles andere auch - nur schreiben geht nicht.(Wenn für euch nicht alles klar sein sollte: Ich bin noch relativer Neuling, der zuvor nur in PHP Webseiten gebaut hat.)

===========================================================

Привет всем, я почти отчаялся почтинеделю сейчас.В настоящее время я пишу веб-сайт на C # и решил отказаться от MVC Page (потому что я не совсем понимаю, что ...).Поэтому я выбрал простое веб-приложение (Visual Studio 2017), и до сих пор мне это нравится.У меня есть классы, как в обычных приложениях WPF, и я до сих пор неплохо справляюсь.Моя проблема: я просто не могу сохранить cookie или переменные сессии.Я уже могу читать куки, а также почти все остальное - только запись невозможна.(Если вам не все ясно: я все еще относительный новичок, который использовал для создания сайтов на PHP.) Кстати: извините за мой возможный плохой английский.

Startup.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Webpage {
    public class Startup {
        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.Configure<CookiePolicyOptions>(options => {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

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

            services.AddHttpContextAccessor();
        }

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

            app.UseStaticHttpContext();

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

            app.UseMvc();
        }
    }
    public static class StaticHttpContextExtensions {
        public static void AddHttpContextAccessor(this IServiceCollection services) {
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
        }

        public static IApplicationBuilder UseStaticHttpContext(this IApplicationBuilder app) {
            var httpContextAccessor = app.ApplicationServices.GetRequiredService<IHttpContextAccessor>();
            System.Web.HttpContext.Configure(httpContextAccessor);
            return app;
        }
    }
}

namespace System.Web {
    public static class HttpContext {
        private static IHttpContextAccessor _contextAccessor;

        public static Microsoft.AspNetCore.Http.HttpContext Current => _contextAccessor.HttpContext;

        internal static void Configure(IHttpContextAccessor contextAccessor) {
            _contextAccessor = contextAccessor;
        }
    }
}

HttpConnection.cs:

using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace Webpage.Classes {
    public class HttpConnection {
        public static IPAddress GetUserIPAddress() {
            return System.Web.HttpContext.Current.Connection.RemoteIpAddress;
        }

        public static string addReplaceCookie(string cookieName, string cookieValue) {
            System.Web.HttpContext.Current.Response.Cookies.Append(cookieName, cookieValue, new CookieOptions {
                Expires = DateTime.Now.AddDays(1),
                Domain = null
            });
            return System.Web.HttpContext.Current.Request.Cookies[cookieName];
        }
    }
}
...