HttpClient return json response on localhost when application live on server it's return html - asp.net

I'm calling API using HttpClient below code running fine on localhost but when it's live on server it's return html response.
here is the code i'm using
public async Task<ActionResult> getPost()
{
string url = "https://www.instagram.com/p/Bg9DwFYHARK/?__a=1";
HttpClient _client = new HttpClient();
var Response = await _client.GetAsync(url);
if (Response.IsSuccessStatusCode)
{
var Result = Response.Content.ReadAsStringAsync().Result;
//here in **Result** i've received html instead of json or when i received html instead
of json got error on DeserializeObject.
var Jsonresult = JsonConvert.DeserializeObject<post>(Result);
return Json(new { isValid = false, error = "post found", obj = Jsonresult }, JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { isValid = false, error = "post not found" }, JsonRequestBehavior.AllowGet);
}
}

This method response is JSON.
string uri = "https://www.instagram.com/p/Bg9DwFYHARK/?__a=1";
private static async Task<ActionResult> getPost(string uri)
{
var webRequest = WebRequest.Create(uri) as HttpWebRequest;
if (webRequest == null)
{
return;
}
webRequest.ContentType = "application/json";
webRequest.UserAgent = "Nothing";
using (var s = webRequest.GetResponse().GetResponseStream())
{
using (var sr = new StreamReader(s))
{
// var contributorsAsJson = sr.ReadToEnd();
var contributors = JsonConvert.DeserializeObject<Create a list >(contributorsAsJson);
// contributors.ForEach(Console.WriteLine);
return contributors;
}
}
}
I get out put is:
{"graphql":{"shortcode_media":{"__typename":"GraphImage","id":"1746568728937235530","shortcode":"Bg9DwFYHARK","dimensions":{"height":1080,"width":1080},"gating_info":null,"fact_check_overall_rating":null,"fact_check_information":null,"sensitivity_friction_info":null,"media_overlay_info":null,"media_preview":"ACoqytpjBOM+tQs6t07nvxwOn4889q2TDuGKzrfT2kkKtkBDz7j2PT0/OlpuUm7cvQqrbSS/cBb6D/IqI8DHfvXZiVI12qpBA+7xwPr0/WueMXm3LMBx94jryf0PrSTdwaVrlSKMsKd5ZrYji7n8B/8AWp3k+wp3ILSKT0FBkW2YM/AcEZ9xz+o4+uBVgyBSB26VDcWgnYFuVUEbfr3B9Qarl0HcRrgqQWVlX5snjIBxgsOw9fTFR2xEu+QdHbj6DgH8earPayvuUuXXHTGC2OgZv5461pQRGKNY+PlABx69/wBamKvuVJ9iMgikqwy4qPZSasJambblpm3dlP5n69x/9atgetZ1h/qV/H+ZrQHQfhWl7tk2JqY7bQT6UtRvTAN2aZUSnn8am2L6D8qdk9xbH//Z","display_url":"https://instagram.fcok6-1.fna.fbcdn.net/v/t51.2885-15/e35/29400587_173904939930435_4131401846013034496_n.jpg?_nc_ht=instagram.fcok6-1.fna.fbcdn.net&_nc_cat=103&_nc_ohc=cgtRDraKPGoAX_a9AvI&oh=fc8640215bbe4a5003bbaf694113951c&oe=5F2FFE5A","display_resources":[{"src":"https://instagram.fcok6-1.fna.fbcdn.net/v/t51.2885-15/sh0.08/e35/s640x640/29400587_173904939930435_4131401846013034496_n.jpg?_nc_ht=instagram.fcok6-1.fna.fbcdn.net&_nc_cat=103&_nc_ohc=cgtRDraKPGoAX_a9AvI&oh=e971123fdc4eb19abe4a96b35195dd9f&oe=5F30CFBD","config_width":640,"config_height":640},{"src":"https://instagram.fcok6-1.fna.fbcdn.net/v/t51.2885-15/sh0.08/e35/s750x750/29400587_173904939930435_4131401846013034496_n.jpg?_nc_ht=instagram.fcok6-1.fna.fbcdn.net&_nc_cat=103&_nc_ohc=cgtRDraKPGoAX_a9AvI&oh=33fe7c336ecff4205e161452adfc7ecf&oe=5F31703D","config_width":750,"config_height":750},{"src":"https://instagram.fcok6-1.fna.fbcdn.net/v/t51.2885-15/e35/29400587_173904939930435_4131401846013034496_n.jpg?_nc_ht=instagram.fcok6-1.fna.fbcdn.net&_nc_cat=103&_nc_ohc=cgtRDraKPGoAX_a9AvI&oh=fc8640215bbe4a5003bbaf694113951c&oe=5F2FFE5A","config_width":1080,"config_height":1080}],"accessibility_caption":"Photo by Ateeq Khalil in Salt N Pepper Liberty. Image may contain: 1 person","is_video":false,"tracking_token":"eyJ2ZXJzaW9uIjo1LCJwYXlsb2FkIjp7ImlzX2FuYWx5dGljc190cmFja2VkIjp0cnVlLCJ1dWlkIjoiZWQ2ZjUxNTZjMjc5NDU5MzlmMmQ1MTQzZDBhZmIyYjYxNzQ2NTY4NzI4OTM3MjM1NTMwIn0sInNpZ25hdHVyZSI6IiJ9","edge_media_to_tagged_user":{"edges":[]},"edge_media_to_caption":{"edges":[]},"caption_is_edited":false,"has_ranked_comments":false,"edge_media_to_parent_comment":{"count":0,"page_info":{"has_next_page":false,"end_cursor":null},"edges":[]},"edge_media_to_hoisted_comment":{"edges":[]},"edge_media_preview_comment":{"count":0,"edges":[]},"comments_disabled":false,"commenting_disabled_for_viewer":false,"taken_at_timestamp":1522427239,"edge_media_preview_like":{"count":19,"edges":[]},"edge_media_to_sponsor_user":{"edges":[]},"location":{"id":"1730525857251432","has_public_page":true,"name":"Salt N Pepper Liberty","slug":"salt-n-pepper-liberty","address_json":"{\"street_address\": \"48 Commercial Zone Liberty Market, Gulberg III\\u060c\", \"zip_code\": \"\", \"city_name\": \"Lahore, Pakistan\", \"region_name\": \"\", \"country_code\": \"PK\", \"exact_city_match\": false, \"exact_region_match\": false, \"exact_country_match\": false}"},"viewer_has_liked":false,"viewer_has_saved":false,"viewer_has_saved_to_collection":false,"viewer_in_photo_of_you":false,"viewer_can_reshare":true,"owner":{"id":"5394358177","is_verified":false,"profile_pic_url":"https://instagram.fcok6-1.fna.fbcdn.net/v/t51.2885-19/s150x150/29402856_149619235868663_6235876322871083008_n.jpg?_nc_ht=instagram.fcok6-1.fna.fbcdn.net&_nc_ohc=gSyry9Wj5UkAX_bQlzD&oh=bdc6a6b82077c8e461aedbaffa7e49db&oe=5F32308B","username":"ateeq.khalil","blocked_by_viewer":false,"restricted_by_viewer":null,"followed_by_viewer":false,"full_name":"Ateeq Khalil","has_blocked_viewer":false,"is_private":false,"is_unpublished":false,"requested_by_viewer":false,"edge_owner_to_timeline_media":{"count":7},"edge_followed_by":{"count":175}},"is_ad":false,"edge_web_media_to_related_media":{"edges":[]},"edge_related_profiles":{"edges":[]}}}}

Related

StatusCode error 500 when sending a POST resquest in XF

I'm writing an API in EF to send FCM notifications:
[HttpPost]
public void PushNotificationToFCM(string deviceTokens, string title, string body, object data, string linkdirection)
{
...
// This registration token comes from the client FCM SDKs.
var registrationToken = deviceTokens;
// See documentation on defining a message payload.
var message = new Message()
{
Apns = new ApnsConfig { Aps = new Aps { ContentAvailable = true, Sound = "default" } },
Data = new Dictionary<string, string>()
{
{ "link", linkdirection },
},
Token = registrationToken,
Notification= new FirebaseAdmin.Messaging.Notification()
{
Title = title,
Body = body,
}
};
// Send a message to the device corresponding to the provided
// registration token.
string response = FirebaseMessaging.DefaultInstance.SendAsync(message).Result;
// Response is a message ID string.
Debug.WriteLine("Successfully sent message: " + response);
}
I tried on Postman or Swagger everything works fine.
I proceed to write the send command in XF:
.xaml.cs
protected async void SendFirebase()
{
string devicetoken = listDeviceID.deviceidphone;
string titlefirebase = "Title";
string bodyfirebase = "Description";
string linkfirebase = "https://applink/..";
await _apiService.AddNotifyFirebase(devicetoken, titlefirebase, bodyfirebase, linkfirebase);
}
public async Task AddNotifyFirebase(string devicetoken, string titlefirebase, string bodyfirebase, string linkfirebase)
{
var model = new
{
devicetoken = devicetoken,
titlefirebase = titlefirebase,
bodyfirebase = bodyfirebase,
linkfirebase = linkfirebase,
};
var json = JsonConvert.SerializeObject(model);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var request = new HttpRequestMessage(HttpMethod.Post, "https://linkapi/api/SendNotifyDeviceFirebase");
request.Content = content;
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
var responseBody = await response.Content.ReadAsStringAsync();
}
}
However I get the error: StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.NSUrlSessionHandler+NSUrlSessionDataTaskStreamContent, ....
Where did I go wrong? Looking forward to everyone's help. Thank you!
Update
I check on Swagger:
Everything seems fine!
I then changed the send command back:
public async Task AddNotifyFirebase(string devicetoken, string titlefirebase, string bodyfirebase, string linkfirebase)
{
var request = new HttpRequestMessage(HttpMethod.Post, "https://xxxxxx/api/SendNotifyDeviceFirebase?deviceTokens=" + devicetoken + "&title=" + titlefirebase + "&body=" + bodyfirebase + "&linkdirection=" + linkfirebase);
//request.Headers.Add("Accept-Encoding", "gzip");
//request.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain; charset=utf-8");
HttpResponseMessage response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
var responseBody = await response.Content.ReadAsStringAsync();
}
}
I get the error again: StatusCode: 415, ReasonPhrase: 'Unsupported Media Type'
I have handled the problem. Thank you all
public async Task AddNotifyFirebase(NotifyFireBase NotifyFireBaseAdd)
{
var urlput = "......";
HttpClient client = new HttpClient();
var content = NotifyFireBaseAdd;
var stringContent = new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8, "application/json");
await client.PostAsync(urlput, stringContent);
}

How can I make proper request for the Identity Server Token Endpoint?

I tried to send an api call to the identity server via .net 6 console application.
Here is the request:
public static async Task<WorkflowResponse> PostRequestToIdentityAsync()
{
var url = "http://didentity/connect/token";
IdentityRequestDataVM identityRequestDataVM = new IdentityRequestDataVM();
identityRequestDataVM.username = "csm";
identityRequestDataVM.password = "MjAyMjox";
identityRequestDataVM.grant_type = "password";
identityRequestDataVM.scope = "m_gln m_msd";
string jsonString = JsonConvert.SerializeObject(identityRequestDataVM);
using (var httpClient = new HttpClient())
{
var request = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri(url),
Content = new StringContent(jsonString),
Headers =
{
{"X-Login","override"}
}
};
var user = "gclt";
var password = "glsrt";
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
request.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes($"{user}:{password}")));
HttpResponseMessage message = await httpClient.SendAsync(request);
if (message.StatusCode == System.Net.HttpStatusCode.OK)
{
var contents = await message.Content.ReadAsStringAsync();
WorkflowResponse workflowResponse = JsonConvert.DeserializeObject<WorkflowResponse>(contents);
return workflowResponse;
}
else
{
throw new Exception(await message.Content.ReadAsStringAsync());
}
}
}
But, it returned 400 err code (Bad request), is there any mistake in the code snippet ?
It is working fine with postman.

ASP.NET Core convert http response message to IEnumerable

I am trying to convert a http response message into an IEnumerable, but I get the error:
JsonException: The JSON value could not be converted to System.Collections.Generic.IEnumerable 1[MyProject.Models.MyClass]. Path: $ | LineNumber: 0 | BytePositionInLine: 1.
Here is my code:
[HttpGet]
public async Task<IEnumerable<MyClass>> GetAsync()
{
var httpRequestMessage = new HttpRequestMessage(
HttpMethod.Get,
"https://xxx/api/123")
{
Headers =
{
{ HeaderNames.Authorization, "password" },
}
};
var httpClient = _httpClientFactory.CreateClient();
var httpResponseMessage = await httpClient.SendAsync(httpRequestMessage);
if (httpResponseMessage.IsSuccessStatusCode)
{
using var contentStream =
await httpResponseMessage.Content.ReadAsStreamAsync();
Ipads = await JsonSerializer.DeserializeAsync
<IEnumerable<MyClass>>(contentStream); // HERE IS WHERE THE ERROR HITS
}
return MyClasses;
}
Here is the same GET but in Postman working:
Thanks beforehand!
Best regards Max
You need to await the content from the HttpResponseMessage as string.
var responseContent = await httpResponseMessage.Content.ReadAsStringAsync();
var model = JsonConvert.DeserializeObject<MyClass>(responseContent);

Xamarin Http Request Timeout Issue

I have a mobile application based on Xamarin and a Web API based on .Net Core. Mobile app consumes methods of Web API via HttpClient. The code below is my base method to call any Web API method and the point is I want to set a timeout but could not achieved to set the exact timeout value whatever I have implemented. Tried Timespan.FromSeconds() or TimeSpan.FromMilliseconds() etc. When client makes a request to Web API, a loader is displayed to lock UI and removed after API response. Some clients gave me a feedback that the loader is displayed forever and request never ends. Maybe, the server is unreachable in this particular time or internet connection is broken for client etc. All I want to set a timeout and break the request and display an alert message to client. Of course, I googled and tried too much as mentioned but no result. If anyone can help me, will be appreciated.
public async Task<BaseResponseModel> Post(BasePostModel postModel)
{
var responseModel = new BaseResponseModel();
var json = postModel.ToString();
var jsonParam = new StringContent(json, Encoding.UTF8, "application/json");
var isPosted = true;
var clientHandler = new HttpClientHandler()
{
AllowAutoRedirect = true,
};
var url = GetURL(postModel.UrlKey);
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore,
ContractResolver = new DefaultContractResolver(),
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
};
var client = new HttpClient(clientHandler);
//client.Timeout = TimeSpan.FromSeconds(10);
//var cancellationTokenSource = new CancellationTokenSource();
//cancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(10));
client.DefaultRequestHeaders.Add("Accept", "application/json");
client.DefaultRequestHeaders.Add("X-Env", "MOBILE_API");
AttachToken(ref client, responseModel.Id);
try
{
if (Preferences.ContainsKey("UserJwtExprieDate"))
{
var expiryDate = Preferences.Get("UserJwtExprieDate", null);
if (DateTime.Now > DateTime.Parse(expiryDate))
{
Preferences.Remove("UserJwtExprieDate");
Preferences.Remove("HomePageInformation");
int index = Xamarin.Forms.Application.Current.MainPage.Navigation.NavigationStack.Count - 1;
Page currPage = Xamarin.Forms.Application.Current.MainPage.Navigation.NavigationStack[index];
if (currPage as SigninForFactorOne != null)
{}
else
{
App.LogoutUser();
}
}
else
{
var response = await client.PostAsync(url, jsonParam);
if (response.IsSuccessStatusCode)
{
string result = response.Content.ReadAsStringAsync().Result;
var resultModel = JsonConvert.DeserializeObject<BaseResponseModel>(result, settings);
if (resultModel.ErrorType == APIErrorTypes.NULL)
{
if (resultModel.IsSucceed)
{
responseModel.Data = resultModel.Data;
}
else
{
responseModel.Error = resultModel.Error;
}
responseModel.Message = resultModel.Message;
}
else
{
responseModel.Error = "Token Expried Date.";
Preferences.Remove("UserJwtExprieDate");
Preferences.Remove("HomePageInformation");
App.LogoutUser();
}
}
else
{
new AppException(new Exception("HTTP Client response is not succeed!"), responseModel.Id);
isPosted = false;
}
}
}
else
{
var response = await client.PostAsync(url, jsonParam);
if (response.IsSuccessStatusCode)
{
string result = response.Content.ReadAsStringAsync().Result;
var resultModel = JsonConvert.DeserializeObject<BaseResponseModel>(result, settings);
if (resultModel.ErrorType == APIErrorTypes.NULL)
{
if (resultModel.IsSucceed)
{
responseModel.Data = resultModel.Data;
}
else
{
responseModel.Error = resultModel.Error;
}
responseModel.Message = resultModel.Message;
}
else
{
responseModel.Error = "Token Expried Date.";
Preferences.Remove("UserJwtExprieDate");
Preferences.Remove("HomePageInformation");
App.LogoutUser();
}
}
else
{
new AppException(new Exception("HTTP Client response is not succeed!"), responseModel.Id);
isPosted = false;
}
}
}
catch (Exception ex)
{
new AppException(ex, responseModel.Id, 500, "anonymous.user", "Unable to post data to API!");
isPosted = false;
}
finally
{
if (!isPosted)
{
responseModel.Error = AppConfiguration.GetSystemMessage(contactYourSystemAdministratorMessage);
responseModel.Message = AppConfiguration.GetSystemMessage(contactYourSystemAdministratorMessage);
}
}
return responseModel;
}
I've used the solution below to manually set a time-out which works fine.
internal class TimeOutHandler : DelegatingHandler
{
private readonly TimeSpan TimeOut;
public TimeOutHandler(TimeSpan timeOut) => TimeOut = timeOut;
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage req, CancellationToken ct)
{
using (var ctTimeOut = CancellationTokenSource.CreateLinkedTokenSource(ct))
{
ctTimeOut.CancelAfter(TimeOut);
try
{
return await base.SendAsync(req, ctTimeOut.Token);
}
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
{
throw new TimeoutException();
}
}
}
}
How to use
var interval = TimeSpan.FromSeconds(10);
var handler = new TimeOutHandler(interval)
{
InnerHandler = new HttpClientHandler()
};
var client = new HttpClient(handler);
For more information, check out: https://thomaslevesque.com/2018/02/25/better-timeout-handling-with-httpclient/

Reverse proxy in .NET Core Middleware “set-cookie” response does not set in browser and not showing in HttpResponseMessage

Here I am making a reverse proxy server to bypass an ASP.NET web application (following this tutorial). I am trying to read the session ID cookie from HttpResponseMessage. I used a cookie container as well but am unable to find it. Implemented in ASP.NET core invoke method, session is working properly but unable to catch session ID in request or response.
public async Task Invoke(HttpContext context, IBrowserDetector detector)
{
//context.Session.SetString(SessionKeyName, "The Doctor");
var browser = detector.Browser;
var targetUri = BuildTargetUri(context.Request);
if (context.Request.Method != HttpMethod.Get.Method)
{
var remoteIp = context.Connection.RemoteIpAddress;
//var gg= context.Request.Headers.ContainsKey.;
var clienttdatetime = context.Request.Headers["Date"].ToString();
//_logger.LogDebug("Request from Remote IP address: {RemoteIp}", remoteIp);
var badIp = true;
var bytes = remoteIp.GetAddressBytes();
//var testIp = IPAddress.Parse(address);
//if (testIp.GetAddressBytes().SequenceEqual(bytes))
//{
// badIp = false;
// break;
//}
if (remoteIp.IsIPv4MappedToIPv6)
{
remoteIp = remoteIp.MapToIPv4();
}
IPAddress remoteIpAddress = context.Request.HttpContext.Connection.RemoteIpAddress;
string result = "";
if (remoteIpAddress != null)
{
// If we got an IPV6 address, then we need to ask the network for the IPV4 address
// This usually only happens when the browser is on the same machine as the server.
if (remoteIpAddress.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
{
remoteIpAddress = System.Net.Dns.GetHostEntry(remoteIpAddress).AddressList
.First(x => x.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork);
}
result = remoteIpAddress.ToString();
}
if (badIp)
{
//_logger.LogWarning(
// "Forbidden Request from Remote IP address: {RemoteIp}", remoteIp);
//context.Response.StatusCode = StatusCodes.Status403Forbidden;
//return;
}
}
if (targetUri != null)
{
CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
var targetRequestMessage = CreateTargetMessage(context, targetUri);
using (var responseMessage = await _httpClient.SendAsync(targetRequestMessage, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted))
{
IEnumerable<Cookie> responseCookies = cookies.GetCookies(targetUri).Cast<Cookie>();
foreach (Cookie cookie_ in responseCookies)
Console.WriteLine(cookie_.Name + ": " + cookie_.Value);
// ExtractCookiesFromResponse(responseMessage);
context.Response.StatusCode = (int)responseMessage.StatusCode;
CopyFromTargetResponseHeaders(context, responseMessage);
await responseMessage.Content.CopyToAsync(context.Response.Body);
//if(responseMessage.RequestMessage.RequestUri.ToString()== "http://localhost:51125/Menu.aspx")
//{
//Uri uri = new Uri("http://localhost:5000/login.aspx");
//Build the request
//Uri site = targetUri;
// HttpWebRequest request = (HttpWebRequest)WebRequest.Create(site);
// CookieContainer cookiesq = new CookieContainer();
// request.CookieContainer = cookiesq;
// //Print out the number of cookies before the response (of course it will be blank)
// Console.WriteLine(cookiesq.GetCookieHeader(site),"1");
// //Get the response and print out the cookies again
// using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
// {
// Console.WriteLine(cookiesq.GetCookieHeader(site), "2");
// }
// Console.ReadKey();
//}
var cookie = context.Request.Cookies["ASP.NET_SessionId"];
}
return;
}
await _nextMiddleware(context);
}
------------------------------------------------------------------------------------
public static IDictionary<string, string> ExtractCookiesFromResponse(HttpResponseMessage response)
{
IDictionary<string, string> result = new Dictionary<string, string>();
IEnumerable<string> values;
if (response.Headers.TryGetValues("Set-Cookie", out values))
{
SetCookieHeaderValue.ParseList(values.ToList()).ToList().ForEach(cookie =>
{
result.Add(cookie.Name.ToString(), cookie.Value.ToString());
});
}
return result;
}
As far as I can see, you created the HttpClientHandler but didn't use it to build the HttpClient to make your request. You are still using the static _httpClient that nothing knows about the cookie container you created.
This should be the reason why you get the CookieContainer still empty.
Take a look here to learn how to get cookies from an HttpResponseMessage.
CookieContainer cookies = new CookieContainer();
HttpClientHandler handler = new HttpClientHandler();
handler.CookieContainer = cookies;
_httpClient = new HttpClient(handler);
var targetRequestMessage = CreateTargetMessage(context, targetUri);
using (var responseMessage = await _httpClient.SendAsync(targetRequestMessage, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted))
{
//var responseCookies = cookies.GetCookies(targetUri).Cast<Cookie>();
IEnumerable<Cookie> responseCookies = cookies.GetCookies(targetUri).Cast<Cookie>();
foreach (Cookie cookie in responseCookies)
{
if(cookie.Name=="ASP.NET_SessionId")
{
Console.WriteLine(cookie.Name + ": " + cookie.Value);
context.Response.Headers.Add("Set-Cookie", cookie.Name+"="+cookie.Value);
}
}

Resources