如何在ASP .NET Core MVC中将Cookie添加到HTTP请求标头 [英] How add Cookies to http request header in ASP .NET Core MVC

查看:426
本文介绍了如何在ASP .NET Core MVC中将Cookie添加到HTTP请求标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从

我不确定我是否理解这个问题.

如果有该值,只需将其放在标题中

  request.AddHeader("Cookie",value) 

如果要定义.net Core应用程序以允许使用会话Cookie,则可以尝试转到Startup.cs,并在ConfigureServices方法中添加:

  services.AddSession(options =>{options.IdleTimeout = TimeSpan.FromSeconds(int.Parse(_configuration ["Cookies:ExpiresInSecond"])));options.Cookie.Name = _configuration ["Cookies:CookiesName"];options.Cookie.IsEssential = true;options.Cookie.SameSite = SameSiteMode.Unspecified;}); 

_configuration来自.NET Core项目中的appSettings.json文件.

如果您希望为会话Cookie设置一个值,请使用:

  _httpContext.HttpContext.Session.Set(KEY,Encoding.ASCII.GetBytes(VALUE)); 

如果您希望从会话Cookie中获取价值:

  _httpContext.HttpContext.Session.TryGetValue(KEY,out byte [] VALUE_BYTES);var value = VALUE_BYTES == null?":Encoding.ASCII.GetString(VALUE_BYTES); 

如果您希望将刚刚从会话Cookie中提取的值添加到请求标头中,请使用:

  request.AddHeader("Cookie",value) 

希望涵盖一切:)

I need to get token array from https://token.docs.microsoft.com/accesstokens. This can be done by include cookies to the http request header. I already tested with postman. It works.

I have web application with ASP .Net core Mvc. It will authenticate with Azure AD. After user log in i need to send a API request include with 'Cookie' request header.

static async Task<string> SendURI(Uri u, HttpContent c, string token)
        {
            var response = string.Empty;
            using (var client = new HttpClient())
            {

                client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
                HttpRequestMessage request = new HttpRequestMessage
                {
                    Method = HttpMethod.Post,
                    RequestUri = u,
                    Content = c
                };

                HttpResponseMessage result = await client.SendAsync(request);
                if (result.IsSuccessStatusCode)
                {
                    response = result.StatusCode.ToString();
                }
            }
            return response;
        }

This is how I send the request. Its working fine for other request without cookie request header. But I need to know how to add cookies to this http request from my app. https://docs.microsoft.com/en-us/rest/api/resources/tenants/list#code-try-0 in this doc they using this method. I need the same effort with my app. They send post request to https://token.docs.microsoft.com/accesstokens this with cookie header.

screenshot of sample request

UPDATE: adding header cookie to http request is can be done by help of post man code.

Now I face a challenge with creating custom cookie like ms doc using.

cookie sample ss

How can I create customer cookie inside startup.cs file? for the content value what should to be included?

services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromSeconds(20);
                options.Cookie.Name = ".TokenAuthCookies";
                options.Cookie.Path = "/";
                options.Cookie.Domain = ".docs.microsoft.com";
                options.Cookie.IsEssential = true;
                options.Cookie.SameSite = SameSiteMode.Unspecified;
            });

How I change my above code accordingly to achieve this?

解决方案

Here's a fun life hack when using Postman:

EDIT:

I'm not sure if I understand the question.

If you have the value, just put it in the header

request.AddHeader("Cookie",value)

If you want to define your .net Core app to allow the use of Session Cookies you can try going to Startup.cs and in the ConfigureServices method add:

services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromSeconds(int.Parse(_configuration["Cookies:ExpiresInSecond"]));
                options.Cookie.Name = _configuration["Cookies:CookiesName"];
                options.Cookie.IsEssential = true;
                options.Cookie.SameSite = SameSiteMode.Unspecified;
            });

the _configuration is taken from the appSettings.json file in your .NET Core project.

EDIT 2:

If you wish to set a value to your session Cookie, use:

_httpContext.HttpContext.Session.Set(KEY, Encoding.ASCII.GetBytes(VALUE));

If you wish to get a value from your session Cookie:

_httpContext.HttpContext.Session.TryGetValue(KEY, out byte[] VALUE_BYTES);
var value = VALUE_BYTES == null ? "" : Encoding.ASCII.GetString(VALUE_BYTES);

If you wish to add the value you just pulled from Session Cookie to your request header use:

request.AddHeader("Cookie",value)

Hope that covers everything :)

这篇关于如何在ASP .NET Core MVC中将Cookie添加到HTTP请求标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆