如何将Blazor项目通过Azure Functions连接至SignalR?
Blazor调用Azure Functions SignalR Negotiate接口的问题解决
核心误解
你当前的问题出在URL路径写法和HttpClient默认行为上:
- Blazor中注入的
HttpClient默认会以当前应用的基地址作为请求基础,若传入的URL不带http/https前缀,会被识别为相对路径,自动拼接当前Blazor项目的URI,这就是请求被追加Blazor地址的原因。 - 对比你的TS代码,它使用带协议的完整
ApiBaseUrl拼接路径,因此不会出现该问题。
解决步骤
使用绝对URL发起请求
必须确保请求URL是包含http://或https://前缀的完整绝对路径,示例代码:var negotiateUrl = "https://your-azure-function-host/negotiate"; signalRConnectionInfo = await Http.GetFromJsonAsync<SignalRConnectionInfo>(negotiateUrl);添加必要的请求头
参考TS代码,需要在请求中携带x-ms-client-principal-id头,Blazor中可通过HttpRequestMessage实现:var request = new HttpRequestMessage(HttpMethod.Get, "https://your-azure-function-host/negotiate"); request.Headers.Add("x-ms-client-principal-id", "your-value-here"); var response = await Http.SendAsync(request); response.EnsureSuccessStatusCode(); signalRConnectionInfo = await response.Content.ReadFromJsonAsync<SignalRConnectionInfo>();可选:配置HttpClient基础地址
若需多次调用Azure Functions,可在Program.cs中配置HttpClient的基础地址,避免重复编写完整URL:builder.Services.AddHttpClient("AzureFunctionsClient", client => { client.BaseAddress = new Uri("https://your-azure-function-host/"); });然后在组件中注入命名HttpClient并使用:
[Inject] private IHttpClientFactory HttpClientFactory { get; set; } // 调用逻辑 var client = HttpClientFactory.CreateClient("AzureFunctionsClient"); var request = new HttpRequestMessage(HttpMethod.Get, "negotiate"); request.Headers.Add("x-ms-client-principal-id", "your-value-here"); // ...后续请求处理
内容的提问来源于stack exchange,提问作者Aaron Manill
相关产品推荐
相关产品推荐

