HttpClient 请求无法识别会话 ASP.NET 来自 razor 的 Core 6 MVC

HttpClient requests not recognizing session ASP.NET Core 6 MVC from razor

不知道还有什么地方可以看,我想要完成的是以下内容

我有一个 ASP.NET Core 6 MVC 应用程序,带有这样的控制器:

public class MyController: Controller
{
    [HttpPost]
    public async Task<IActionResult> SaveNameToDataBase(NameModel nameModel)
    {
        if (CheckSessionIfUserIsLoggedIn())
        {
            PostComment(nameModel)
            return JsonStringThatShowsSuccess
        }
        else 
        { 
            return JsonStringThatShowsAnError 
        }
    }
}

如果我从浏览器调用该方法它工作正常,但是,我正在使用 Blazor 组件以防止整个页面重新加载到 post

@code {    
[Parameter]
public string NewNameToPut { get; set; } = string.Empty;

[Parameter]
public string NewNameExtraParam { get; set; } = string.Empty;

// On click event
private async Task CreateRootComment()
{
    NameModel nameModel = new NameModel(NewNameToPut);

    // update namemmodel
    ...

    // Set up request
    HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, $"{NavigationManager.BaseUri}MyController/SaveNameToDataBase");

    @* Add body to request *@
    request.Content = new StringContent(
        JsonConvert.SerializeObject(nameModel)
    );

    request.Headers.Add("Accept", "application/json");
    request.Headers.TryAddWithoutValidation("Content-Type", "application/json");
    request.Headers.TryAddWithoutValidation("Accept", " text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng");
    //  requestMessage.Headers.TryAddWithoutValidation("Accept-Encoding", "gzip, deflate");
    request.Headers.TryAddWithoutValidation("User-Agent", "Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36");
    request.Headers.TryAddWithoutValidation("Accept-Language", "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7,zu;q=0.6");

    HttpClient client = ClientFactory.CreateClient();
    HttpResponseMessage response = await client.SendAsync(request);
    
    if (response.IsSuccessStatusCode)
    {
       Console.WriteLine(response.Content.ReadAsStringAsync().Result);
    }
}
}

请求已成功发送并触发,但无法识别会话变量。该会话包含一个键值,该键值在用户登录时设置为 true,并且由于某种原因在 HttpClient 执行请求时找不到它,但在浏览器通过鼠标单击、表单提交或 JS 运行时进行时找到它.

也许我从这里漏掉了一些 documentation?任何文章或指南也很有帮助

我实际上已经从 MVC 切换到 MVVM 并且只是注入了所需的服务,以便 blazor 组件可以通过使用独立于控制器 HttpContextAccessor