我有一个我这样称呼的 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 问题吗?