我有一个 WS,我这样称呼:
HttpResponseMessage response = await client.PostAsync(url, new StringContent(json));
WS 将抛出异常(禁止),并且在进行 PostAsync 调用的 Blazor 应用程序中,我将收到 HttpResponseMessage
响应代码为 405,不知道为什么是 405,它应该是 403(Postman 返回 403)。
我已启用 CORS(ServiceStack 代码):
Plugins.Add(new CorsFeature(allowedOrigins: "*",
allowedMethods: "GET, POST, PUT, DELETE, OPTIONS",
allowedHeaders: "*",
allowCredentials: true));
这是我在 PostAsync 之前所做的一些 Console.Writeline:
Failed to load resource: the server responded with a status of 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")
即使这不是你痛苦的原因,最好使用它......
希望这有帮助...
关于c# - HttpResponseMessage.Content.ReasAsString 返回空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56597458/