Why does Device Portal keep crashing?

During the development of Device Manager, I encountered an annoying and weird bug. Whenever I tried to call the APIs in Device Portal through (local loopback) using HTTPS, it crashed with a 403 forbidden, without ever asking me for any server credentials. After digging through a lot of documents, I finally figured out what happened.

In Microsoft’s documents about Device Portal, referred that there is a CSRF Protection in order to protect against CSRF attacks. We need to add a header named ‘X-CSRF-Token’ which contains a unique token or else the request will be rejected. The content of this additional header, according to the document, is delivered from a session cookie. It means we need to set up a connection first to get the cookie. Then add the ‘X-CSRF-Token’ header and copy the cookie’s value to the header.

So the correct setup looks something like

var res = await client.GetAsync(new Uri($"https://{Address}/default.htm"));
if(filter != null)
var cookies = filter.CookieManager.GetCookies(new Uri($"https://{Address}/default.htm")).Where(x => x.Name == "CSRF-Token");
foreach(var i in cookies)
client.DefaultRequestHeaders.Add("X-CSRF-Token", i.Value);

This code initiates a connection to obtain the cookie and add it to the header. After setting up the request header with the proper cookie, everything else works perfectly without any issues.