简体   繁体   English

添加另一个HTTP请求标头C#

[英]To add another http request header c#

Need to know a simple way to add a http header for already existing http request. 需要知道一种简单的方法来为已经存在的http请求添加http标头。

Below is my middle ware code 下面是我的中间件代码

   public class ProviderStateMiddleware
    {
        private ITestOutputHelper _outputHelper { get; }
        private const string ConsumerName = "test";
        private readonly RequestDelegate _next;
        private readonly IDictionary<string, Action> _providerStates;

        public ProviderStateMiddleware(RequestDelegate next)
        {
            _next = next;

            _providerStates = new Dictionary<string, Action>
            {
                {
                    "A session id",
                    getSessionID
                },
            };
        }

        private void getSessionID()
        {



        }

        public async Task Invoke(HttpContext context)
        {

            if (context.Request.Path.Value == "/provider-states")
            {
                this.HandleProviderStatesRequest(context);
                await context.Response.WriteAsync(String.Empty);
            }
            else
            {
                await this._next(context);
            }
        }

        private void HandleProviderStatesRequest(HttpContext context)
        {
            context.Response.StatusCode = (int)HttpStatusCode.OK;

            if (context.Request.Method.ToUpper() == 
    HttpMethod.Post.ToString().ToUpper() &&
                context.Request.Body != null)
            {
                string jsonRequestBody = String.Empty;
                using (var reader = new StreamReader(context.Request.Body, 
    Encoding.UTF8))
                {
                    jsonRequestBody = reader.ReadToEnd();

                }

                var providerState = JsonConvert.DeserializeObject<ProviderState> 
     (jsonRequestBody);

                //A null or empty provider state key must be handled
                if (providerState != null && 
       !String.IsNullOrEmpty(providerState.State) &&
                    providerState.Consumer == ConsumerName)
                {

                    _providerStates[providerState.State].Invoke();
                }
            }
        }
    }
    }

I am new to c# or the http middleware part, please let me know as to where its feasible to add a custom header, like below json. 我是c#或http中间件的新手,请让我知道在哪里可以添加自定义标头,例如json以下。 I read some posts here, but was not much to my understanding. 我在这里阅读了一些帖子,但据我了解并不多。

    {Subscriber-id : "1234"}

From MSDN: 从MSDN:

HttpResponse.OnStarting HttpResponse.OnStarting

Adds a delegate to be invoked just before response headers will be sent to the client. 添加将在响应标头发送到客户端之前要调用的委托。

Add this code to your public async Task Invoke(HttpContext context) function: 将此代码添加到public async Task Invoke(HttpContext context)函数中:

context.Response.OnStarting(() =>
        {
            context.Response.Headers.Add("Key", "Value");
            return Task.CompletedTask;
        });

This was handled with PactVerifierConfig.CustomHeader method, which adds request headers. 这是通过PactVerifierConfig.CustomHeader方法处理的,该方法添加了请求标头。

var config = new PactVerifierConfig
        {

            Outputters = new List<IOutput>
                            {
                                new XUnitOutput(_outputHelper)
                            },
            //Custom header
            CustomHeader = new KeyValuePair<string, string>("testId","test123"),
            // Output verbose verification logs to the test output
            Verbose = true
        };

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

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