.net - 如何使用自定义 WebResponse 创建 WebException

标签 .net asp.net-mvc-4 asp.net-web-api httpwebresponse system.net.webexception

我使用 MVC4 Web API 创建了一个 RESTful 网络服务。如果出现问题,我将抛出 WebException。

throw new WebException("Account not found");

这是处理异常的客户端代码:

private void webClientPost_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        try
        {
            if (e.Error == null)
            {
                // Display result
                textBoxResult.Text = e.Result;
            }
            else
            {
                // Display status code
                if (e.Error is WebException)
                {
                    StringBuilder displayMessage = new StringBuilder();

                    WebException we = (WebException)e.Error;
                    HttpWebResponse webResponse = (System.Net.HttpWebResponse)we.Response;

                    displayMessage.AppendLine(webResponse.StatusDescription);

                    // Gets the stream associated with the response.
                    Stream receiveStream = webResponse.GetResponseStream();
                    Encoding encode = System.Text.Encoding.GetEncoding("utf-8");

                    // Pipes the stream to a higher level stream reader with the required encoding format. 
                    StreamReader readStream = new StreamReader(receiveStream, encode);

                    displayMessage.Append(readStream.ReadToEnd());

                    readStream.Close();

                    textBoxResult.Text = displayMessage.ToString();
                }
            }
        }
        catch (Exception ex)
        {
            textBoxResult.Text = ex.Message;
        }
    }

如您所见,客户端代码正在显示 WebException 中包含的 HttpWebResponse。然而显示的是:

Internal Server Error {"Message":"An error has occurred."}

这不是我的错误消息:-(所以我想我会使用 Mircosoft 指定的 WebException 的替代构造函数 MSDN WebException 4th Constructor

在 MSDN 示例中,他们通过以下方式创建 WebResponse:

MemoryStream memoryStream = new MemoryStream(recvBytes);
getStream = (Stream) memoryStream;

// Create a 'WebResponse' object
WebResponse myWebResponse = (WebResponse) new HttpConnect(getStream);
Exception myException = new Exception("File Not found");

// Throw the 'WebException' object with a message string, message status,InnerException and WebResponse 
throw new WebException("The Requested page is not found.", myException, WebExceptionStatus.ProtocolError, myWebResponse);

但是 .Net Framework 中不存在 HttpConnect :-(。

有谁知道如何使用特定的 WebResponse 创建 WebException? 谢谢, 马特

最佳答案

I am throwing a WebException if something is wrong

哦,不,不要。如果您的 Web API 出现问题,请设置相应的响应状态代码。

例如:

public HttpResponseMessage Get(int id)
{
    var model = this.repository.Get(id);
    if (model == null)
    {
        return Request.CreateErrorResponse(
            HttpStatusCode.NotFound, 
            string.Format("Sorry but we couldn't find a resource with id={0}", id)
        );
    }

    return Request.CreateResponse(HttpStatusCode.OK, model);
}

然后在客户端:

using (var client = new WebClient())
{
    try
    {
        string result = client.DownloadString("http://example.com/api/someresources/123");
    }
    catch (WebException ex)
    {
        // get the status code:
        var response = (HttpWebResponse)ex.Response;
        var statusCode = response.StatusCode;
        // you could also read the response stream:
        using (var reader = new StreamReader(response.GetResponseStream()))
        {
            // now you could read the body
            string body = reader.ReadToEnd();
        }
    }
}

关于.net - 如何使用自定义 WebResponse 创建 WebException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14983708/

相关文章:

c# - 启用 SSL 时 NopCommerce 商店内页未获取

asp.net - 向所有 WebApi 的响应添加额外的 json 结构?

c# - HttpContext 抛出 HttpException

c# - 按值对字典进行排序,该值是具有 DateTime 的对象

asp.net-mvc - Web API 多次或单次调用

基于登录路由的 C# MVC4 登录操作

c# - 禁止 ASP.NET Web API 上具有空值的属性

url - STRAVA API 版本 1 和 2 之间有什么区别以及如何使用 v2 获取 "streams"对象?

c# - 为什么 .Contains 很慢?通过主键获取多个实体的最有效方法?

c# - 使用 C# 进行高质量 JPEG 压缩