简体   繁体   English

当HttpWebRequest.GetResponse抛出WebException时,如何读取返回的自定义错误消息?

[英]How do I read a custom error message returned when HttpWebRequest.GetResponse throws a WebException?

I've a NET.Core API with simple test method: 我有一个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;
    }

}

I need to retrieve the message from a client like this: 我需要从客户端检索消息,如下所示:

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);
}

Now request.GetResponse() as HttpWebResponse returns me: 现在request.GetResponse() as HttpWebResponse返回给我:

The remote server returned an error: (401) Unauthorized.

在此输入图像描述

instead of My custom error . 而不是My custom error Can someone point me in the right direction? 有人能指出我正确的方向吗?

Here's a pared-down example which reads your custom message. 这是一个简化的示例,它会读取您的自定义消息。 Your message is returned in the response stream. 您的消息将在响应流中返回。

try
{
    var response = request.GetResponse() as HttpWebResponse;
}
catch (WebException ex) // this exception is thrown because of the 401.
{
    var responseStream = ex.Response.GetResponseStream();
    using (var reader = new StreamReader(responseStream))
    {
        var message = reader.ReadToEnd();
    }
}

Return an ActionResult 返回一个ActionResult

Task<ActionResult>

You can then wrap up the unauthorized error in an UnauthorizedObjectResult 然后,您可以在UnauthorizedObjectResult中包装未经授权的错误

return Unauthorized(new UnauthorizedObjectResult(errorModel));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 HttpWebRequest.GetResponse()引发不可陷阱的错误 - HttpWebRequest.GetResponse() throws untrappable error HttpWebRequest.GetResponse() 失败时如何获取错误信息 - How to get error information when HttpWebRequest.GetResponse() fails 获取错误“使用HttpWebRequest.GetResponse()进行屏幕抓取时,远程服务器返回错误:(403)禁止” - Getting Error “The remote server returned an error: (403) Forbidden” when screen scraping using HttpWebRequest.GetResponse() HttpWebRequest.GetResponse() 抛出“错误请求”400 错误 - HttpWebRequest.GetResponse() throws “Bad Request” 400 error C#HttpWebRequest.GetResponse()返回错误:(404)找不到 - c# HttpWebRequest.GetResponse() returned an error: (404) Not Found 如果服务器返回200以外的其他值,HttpWebRequest.GetResponse()是否总是抛出WebException吗? - Does HttpWebRequest.GetResponse() always throw a WebException if anything other than 200 is returned by the server? HttpWebRequest.GetResponse方法抛出404异常 - HttpWebRequest.GetResponse methods throws 404 exception 我正在获取WebException:“操作已超时”立即在HttpWebRequest.GetResponse()上 - I am getting WebException: “The operation has timed out” immediately on HttpWebRequest.GetResponse() HTTPWebRequest.GetResponse()抛出连接失败异常 - HTTPWebRequest.GetResponse() throws connection failure exception C#HttpWebRequest.GetResponse - 如何处理非异常与webexception响应的StatusCode用法? - C# HttpWebRequest.GetResponse - how is StatusCode usage handled for a non-exception vs webexception response?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM