我有一个简单的.NET Core API测试方法:
public async Task<IActionResult> TestApi()
{
try
{
throw new UnauthorizedAccessException("My custom error");
return Ok();
}
catch (UnauthorizedAccessException ex)
{
return StatusCode(401,ex.Message);
}
catch (Exception ex)
{
throw;
}
}
我需要从像这样的客户端中检索消息:
var request = WebRequest.Create($"{baseUrl}{url}") as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json";
request.Expect = "application/json";
request.ContentLength = 0;
if (parameters != null)
{
request.ContentLength = serializedObject.Length;
using (var writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(serializedObject);
}
}
var response = request.GetResponse() as HttpWebResponse;
var responseEncoding = Encoding.GetEncoding(response.CharacterSet);
using (var sr = new StreamReader(response.GetResponseStream(), responseEncoding))
{
var result = sr.ReadToEnd();
return JsonConvert.DeserializeObject<T>(result);
}
现在,
request.GetResponse() as HttpWebResponse
返回给我以下内容:The remote server returned an error: (401) Unauthorized.
有没有人能帮我指一下方向? 我想要的不是 自定义错误
,而是...
Response
属性中获取GetResponseStream
。 - Scott Hannen