c# - HttpResponseMessage.Content.ReasAsString 返回一个空字符串
问题描述
我有一个我这样称呼的 WS:
HttpResponseMessage response = await client.PostAsync(url, new StringContent(json));
WS 将抛出一个异常(禁止),在我进行 PostAsync 调用的 Blazor 应用程序中,我将得到一个HttpResponseMessage
响应代码 405,不知道为什么它的 405,它应该是 403(邮递员返回 403)。
我启用了 CORS(ServiceStack代码):
Plugins.Add(new CorsFeature(allowedOrigins: "*",
allowedMethods: "GET, POST, PUT, DELETE, OPTIONS",
allowedHeaders: "*",
allowCredentials: true));
这是我在 PostAsync 之前所做的一些 Console.Writeline:
加载资源失败:服务器响应状态为 405 ()
** 更新 **
这是两种方法:
public async Task<TResponse> PostAsync<TResponse, TRequest>(string requestUri, TRequest request)
{
string url = GetUrl(requestUri);
Console.WriteLine("URI: " + url);
string json = JsonConvert.SerializeObject(request);
Console.WriteLine($"{url} | {json}");
HttpResponseMessage response = await client.PostAsync(url, new StringContent(json));
return await GetResponseOrThrowHttpException<TResponse>(response);
}
private async Task<T> GetResponseOrThrowHttpException<T>(HttpResponseMessage response)
{
Console.WriteLine($"GetResponseOrThrowHttpException: {response.StatusCode}");
string responseString = await response.Content.ReadAsStringAsync();
Console.WriteLine($"GetResponseOrThrowHttpException ContentStringResult: |{responseString}|");
if (!response.IsSuccessStatusCode)
{
Newtonsoft.Json.Linq.JObject jsonObject = Newtonsoft.Json.Linq.JObject.Parse(responseString);
string responseStatusString = jsonObject["ResponseStatus"].ToString();
Console.WriteLine($"GetResponseOrThrowHttpException 4: {responseStatusString}");
ResponseStatus responseStatus = JsonConvert.DeserializeObject<ResponseStatus>(responseStatusString);
Console.WriteLine($"Throwing HttpException: {response.StatusCode} {responseStatus.Message}");
throw new HttpException(response.StatusCode, responseStatus.Message);
}
return JsonConvert.DeserializeObject<T>(responseString);
}
当我尝试获取响应的字符串值时,它是空的:
string responseString = await response.Content.ReadAsStringAsync();
并且responseString
是一个空(长度为0)字符串。
如果我在 Postman 中运行完全相同的请求,我会得到一个有效的响应:
因此,在上图中底部看到的响应 JSON 是我想要在 Blazor 应用程序中使用的,并将其解析为 JSON 对象并从那里继续。我还注意到,我在这里收到了一个 403 错误,这是我预期的,在 Blazor 应用程序中,我收到了 405。
即使我在 WS 端启用了 CORS,这是一个 CORS 问题吗?
解决方案
我想您的内容应该这样发布:
new StringContent(json, Encoding.UTF8, "application/json")
即使这不是你痛苦的原因,最好使用它,这样......
希望这可以帮助...
推荐阅读
- javascript - position: fixed 不会将元素固定在元素的底部
- reactjs - VS Code 绝对路径使用 js/tsconfig.json 自动完成和点击查看定义
- python - 使用字典有条件地格式化列(熊猫)
- java - Java Swing 滑块不弹出问题
- python - 在数据类中加载递归字典时出现 ForwardReference NameError
- python - Django - 'UserViewPermissionClass' 对象没有具有自定义权限的属性'authenticate'
- php - 我的 Post 模型怎么能有 2 个不同的路由键名称?(拉拉维尔)
- python - 如何将对象添加到类中,然后在不更改原始对象的情况下对其进行更改?[初学者]
- django - API Django Rest Framework 上的多对多字段 POST 请求
- css - 按钮的背景颜色没有在 React 中立即更新,其他 css 属性工作正常