English 中文(简体)
IHttpContextAccessor.HttpContext.Response.Cookies 收集是空的,上诉人不工作
原标题:IHttpContextAccessor.HttpContext.Response.Cookies Collection is empty and Append does not work

我有1个“网络核心6”网络应用,使用“raz”网页。 我将前端改为“javascript UI”,并增加了该项目的控制人员,为Ajax电话提供服务。 管制人员要求管理人员采用正常的扶养注射(DI)的商业逻辑。

在现有的网页上,我打电话给一位使用, 采用DI。 它一直在工作,我看到能够有6个厨师。

If I call the same code in the manager class from the controllers using one of the Ajax calls - the cookies collection is empty. Furthermore, if I add the basic code below to add a cookie, as a test inline to the existing code, no cookie is visible after the code has processed (and with no errors).

_httpContextAccessor.HttpContext.Response.Cookies.Append("Test", "TestValue");

I am using the DI code below in my Startup.cs

services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

and have tried adding

services.AddHttpContextAccessor();

并且我还试验了各种CookieOptions,但迄今没有uck。

是否有任何想法说明为什么守则在从控制者手中操作时不发挥作用,而是从网页上操作?

ADDED (per Guru request):

Here is the code in the manager:

public class AppManager : IAppManager
{
  private readonly IHttpContextAccessor _httpContextAccessor;

  public AppManager(IHttpContextAccessor httpContextAccessor )
  {
    _httpContextAccessor = httpContextAccessor;
  }

  public string ReadCookie(string key)
  {  
    // ADDED THIS LINE BELOW - BUT IT DOES NOTHING
    // STARTS WITH 0 COOKIES AND IS 0 COOKIES EVEN AFTER THE APPEND
    _httpContextAccessor.HttpContext.Response.Cookies.Append("Test", "TestValue");

    var data = _httpContextAccessor.HttpContext.Request.Cookies[key];

    return data;
  }

  public void WriteCookie(string key, string value, int? daysToPersist = null)
  {
    // HAVE TRIED VARIOUS OPTIONS HERE
    var options = new CookieOptions 
    { 
        SameSite    = SameSiteMode.None,
        Secure      = true,
        IsEssential = true,
        HttpOnly    = false
    };

    if (daysToPersist > 0)
        options.Expires = DateTime.Now.AddDays((double)daysToPersist);
    else
        options.Expires = DateTime.Now.AddSeconds((double)60);

    _httpContextAccessor.HttpContext.Response.Cookies.Append(key, value, options);

  }

  public void DeleteCookie(string key)
  {
    _httpContextAccessor.HttpContext.Response.Cookies.Delete(key);
  }

}

Here is the code in the Controller:

public Guid GetUserGuidFromCookie()
{
    string userGuidString = ReadCookie(UserGuidKey);
    if (!Guid.TryParse(userGuidString, out Guid userGuid))
    {
        userGuid = Guid.NewGuid();
        WriteCookie(UserGuidKey, userGuid.ToString(), 14);
    }
    return userGuid;
}

增加方案 7/28/2023

public class Program
{
   public static void Main(string[] args)
   {
       CreateHostBuilder(args).Build().Run();
   }

   public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
}

Addedstartup.cs 7/28/2023

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

 public IConfiguration Configuration { get; }

 public void ConfigureServices(IServiceCollection services)
 {
    services.AddControllers()
            .AddJsonOptions(options =>
                {
                      options.JsonSerializerOptions.PropertyNamingPolicy = null;
                }
            );

    services.AddRazorPages()  //.AddRazorRuntimeCompilation()
            .AddRazorOptions(options =>
            {
                options.PageViewLocationFormats.Add("/Pages/DisplayTemplates/{0}.cshtml");
            });


    services.AddSingleton<IAppSettings>(Configuration.GetSection("App").Get<AppSettings>());
    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();         
    
    services.AddScoped<IAppManager, AppManager>();


    services.AddCors(o => o.AddPolicy("ApiPolicy", builder =>
    {
        builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader();
    }));

    services.AddHttpContextAccessor();

 }

 public void Configure( IApplicationBuilder app, IWebHostEnvironment env,
                        IDataRepo dataRepo)
 {
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Error");  
        app.UseHsts();
    }

    app.UseHttpsRedirection();

    app.UseStaticFiles();

    app.UseRouting();

    app.UseCors();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
        endpoints.MapRazorPages();
    });
  }
 }
问题回答

Any ideas as to why the code is not working when being run from the controllers but works from the web pages?

确实,根据我的调查和测试,你正在经历这一问题,因为国际移民组织援引错误。

首先,在您的节目.cs文档中,您的编号为<代码>AppManager>。

另一个重要要点是,你不需要登记<条码>。 你这样做的方式。 你可以做以下工作:

builder.Services.AddHttpContextAccessor();

最重要的是,虽然与你的申请国合作,但如果你使用TryAddSingleton/a> http://www.un.org。 这就是单一州服务的设计。

因此,根据您的设想和背景,您应使用AddScoped Service,以便保持贵国的一贯性,而不是凌驾于以前的初始化。

<>Solution:

让我总结一下,我以如下方式使用你的法典,并按预期开展工作:

1. 更新撰稿人库齐的配置:

var options = new CookieOptions
            {
               // SameSite = SameSiteMode.None,
                Secure = true,
                IsEssential = true,
                HttpOnly = false
            };

“enter像

<>说明: 如果你使用<代码>SameSiteMode.None,你还必须确定“HttpOnly”财产。 co将只与https合作。 但是,如果你想要把https定为虚假,那么你可以评论。 SameSite = SameSiteMode.None . 请参看这份正式文件

方案:

在您的《法典》中,您有“AppManager DI”的注册号码,而且您可以登记“AddHttpContextAccessor”如下:

var builder = WebApplication.CreateBuilder(args);


builder.Services.AddScoped<IAppManager, AppManager>();

builder.Services.AddControllersWithViews();

builder.Services.AddHttpContextAccessor();

Controller:

public class CookieManagerController : Controller
    {
        private readonly IAppManager _cookieManager;

        public CookieManagerController(IAppManager appManager)
        {
            _cookieManager = appManager;
        }
        public IActionResult Index()
        {
            _cookieManager.WriteCookie("TestCookieKey", "Kiron Test", 30);
            ViewBag.CookieName = _cookieManager.ReadCookie("TestCookieKey");
            return View();
        }
    }

Output:

“enterhchr

“entergraph

<>说明: 请





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签