Adding a session value while calling a web API method using HttpClient and trying to call another web API method in the same controller with Xhr request, the session value is returned as null or not available. Please check the below code snippet
Index.razor
@inject IJSRuntime JS
<button @onclick="HttpClientCall">Read</button>
<button @onclick="XhrCall">Client Call1</button>
@code {
static HttpClientHandler handler = new HttpClientHandler { UseCookies = true };
HttpClient HttpClient = new HttpClient(handler);
async Task HttpClientCall()
{
await HttpClient.PostAsync("https://localhost:44301/api/Test/Test1", null);
}
async Task XhrCall()
{
await JS.InvokeVoidAsync("createXhr");
}
}
Host.cshtml
<script>
window.createXhr = () => {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () { };
xhr.open('GET', 'https://localhost:44301/api/Test/Test2');
xhr.send()
};
</script>
Controller
[Route("Test1")]
public void Test1(string args)
{
HttpContext.Session.SetString("key", "value");
}
[Route("Test2")]
public void Test2(string args)
{
string value = HttpContext.Session.GetString("key"); // value becomes null here
}