Blazor Web客户端SendAsync()无法获取服务器返回数据求助
Blazor客户端HttpClient.SendAsync无法获取服务器响应
我在Blazor WebApplication(客户端)中创建了一个表单,提交后数据会发送至服务器处理。服务器需要返回操作是否成功的响应,但调用SendAsync()方法时无法获取到任何服务器返回的数据。
有问题的客户端代码如下:
string json = <序列化后的对象>; var request = new HttpRequestMessage(HttpMethod.Post, "https://<服务器地址>"); request.Content = new StringContent(json); request.SetBrowserRequestMode(BrowserRequestMode.NoCors); using (var client = new HttpClient()) { var response = await client.SendAsync(request).ConfigureAwait(false); bool isSuccessCode = response.IsSuccessStatusCode; // 此处值为false string responseStr = await response.Content.ReadAsStringAsync().ConfigureAwait(false); Console.WriteLine(responseStr); // 输出空字符串 if (responseStr == "Success") return true; else return false; }
运行后发现response变量仅包含默认值(0和null),无有效数据,IsSuccessStatusCode为false,读取响应内容得到空字符串。
但在控制台应用中使用相同代码(移除CORS相关配置)测试时,却能正常获取服务器返回的预期响应:
// 此代码可正常运行 internal static async Task<string> Post(string url) { var request = new HttpRequestMessage(HttpMethod.Post, url); request.Content = new StringContent(data); using var client = new HttpClient(); var result = await client.SendAsync(request).ConfigureAwait(false); return await result.Content.ReadAsStringAsync().ConfigureAwait(false); // 返回正常响应 }
内容的提问来源于stack exchange,提问作者Ala Ndala
相关产品推荐
相关产品推荐

