Cookie在.NET Core API中始终为空

时间:2018-10-18 21:44:48

标签: api cookies .net-core asp.net-core-2.0 httpcontext

我有一个.NET Core API,我想实现一个验证码功能。不幸的是,cookie似乎不起作用,因为始终会得到一个空值。

启动文件:

公共类启动     {         公共启动(IConfiguration配置)         {             配置=配置;         }

    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
        services.AddScoped<ICaptchaService, CaptchaService>();

        services.AddDistributedMemoryCache();

        services.AddSession(options =>
        {
            // Set a short timeout for easy testing.
            //options.IdleTimeout = TimeSpan.FromSeconds(3000);
            options.Cookie.HttpOnly = false;
        });

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

    }

    // 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");
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        //app.UseCookiePolicy();
        app.UseSession();
        //app.UseHttpContextItemsMiddleware();
        app.UseMvc();
    }
}

设置cookie(加载验证码时):

    [HttpGet("{name}", Name = "GetCaptcha")]
    public IActionResult GetCaptcha(string name)
    {
        var newCaptcha = _captchaService.CreateNewCaptcha(5);
        var newCaptchaImage = _captchaService.CreateCaptchaImage(newCaptcha);

        //Return the captcha cookie
        HttpContext.Response.Cookies.Append(
            name,
            JsonConvert.SerializeObject(newCaptcha, Formatting.None, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() })
        );          


        return Ok(newCaptchaImage);
    }

我的模型(提交验证码时):

var captchaJson = HttpContext.Request.Cookies[name];

我不知道为什么这不起作用。有人可以告诉我我在做什么错。

0 个答案:

没有答案