繁体   English   中英

在请求标头中包含来自响应标头的 cookie

[英]Include cookie from response headers in request headers

我在 Traefik 反向代理后面运行 .NET Core 应用程序的多个实例。 当用户访问网站时,Traefik 会发回 StickyCookie(在 Set-Cookie 中):

在此处输入图像描述

它告诉客户端 Traefik 背后的哪个服务器接受了他的请求。 如果我们想再次向同一台服务器发送请求,我们还必须在请求中包含 cookie。

如何在 .NET Core 中实现中间件,它将 append StickyCookie 字段应用于每个请求? 它应该包含与从先前响应中收到的相同的 StickyCookie。

基本上,我想实现与以下 Linux 命令相同的效果:

curl -v --cookie "StickyCookie=http://10.0.2.75:80" http://example.com:5000

可以注册中间件以在响应 header 中发送任何内容。 可以在startup.cs文件的Configure方法中注册中间件:

  app.UseMiddleware<CustomHeader>();

然后您的 CustomHeader class 可以

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

namespace PEG.Api.Middleware
{
    public class CustomHeader
    {
        private readonly RequestDelegate _next;

        public CustomHeader(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            //you can add your stickyCookie in the dictionary
            var dictionary = new Dictionary<string, string[]>()
            {
                /* add your sticky cookie here. An example below
                 {
                    "Access-Control-Allow-Credentials",new string[]{"true" }
                }*/
            };

            //To add Headers AFTER everything you need to do this
            context.Response.OnStarting(state => {
                var httpContext = (HttpContext)state;
                foreach (var item in dictionary)
                {
                    httpContext.Response.Headers.Add(item.Key, item.Value);
                }
                return Task.FromResult(0);
            }, context);

            await _next(context);
        }
    }
}

You could get the StickyCookie in response header in middleware and then save it into Session , then you could retrieve the data from session and add it to request header.

public class AddHeaderMiddleware
{
    private readonly RequestDelegate _next;

    public AddHeaderMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context)
    {

        var data = context.Session.GetString("StickyCookie");

        context.Request.Headers.Add("StickyCookie", data);

        context.Response.OnStarting(state =>
        {
            var httpContext = (HttpContext)state;
            var cookies = httpContext.Response.Headers["Set-Cookie"].ToString().Split(";");
            if (cookies.Length > 0)
            {
                foreach (var item in cookies)
                {
                    if (item.Split("=")[0] == "StickyCookie")
                    {
                        var cookie = item.Split("=")[1];
                        httpContext.Session.SetString("StickyCookie", cookie);
                    }
                }
            }
            return Task.FromResult(0);
        }, context);

        await _next(context);
    }
}

public static class AddHeaderMiddlewareExtensions
{
    public static IApplicationBuilder UseAddHeader(
        this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<AddHeaderMiddleware>();
    }
}

在 Startup.cs

 public void ConfigureServices(IServiceCollection services)
    {
        services.AddDistributedMemoryCache();

        services.AddSession(options =>
        {
            //// Set a short timeout for easy testing.
            //options.IdleTimeout = TimeSpan.FromMinutes(10);
            //options.Cookie.HttpOnly = true;
            //// Make the session cookie essential
            options.Cookie.IsEssential = true;
        });
 }
public void Configure(IApplicationBuilder app)
{
     //...
     app.UseSession();
     app.UseAddHeader();
     //...
}

检查动作:

var header = HttpContext.Request.Headers;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM