Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9314509
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 19, 20262026-06-19T02:09:03+00:00 2026-06-19T02:09:03+00:00

I have created a RESTful web service using MVC4 Web API. I am throwing

  • 0

I have created a RESTful web service using MVC4 Web API. I am throwing a WebException if something is wrong.

throw new WebException("Account not found");

Here’s the client code that handles the exception:

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

As you can see, the client code is displaying the HttpWebResponse that is contained with in the WebException. However what is displayed is:

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

This is not my error message 🙁 So I thought I would use an alternative constructor to the WebException as specified by Mircosoft MSDN WebException 4th Constructor

In the MSDN example, they create a WebResponse by:

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

But the HttpConnect does not exist in the .Net Framework :-(.

Does anyone know how to create a WebException with a specific WebResponse?
Thanks,
Matt

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-19T02:09:04+00:00Added an answer on June 19, 2026 at 2:09 am

    I am throwing a WebException if something is wrong

    Oh no, don’t. If something gets wrong in your Web API set the corresponding response status code.

    For example:

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

    and then on the client:

    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();
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have created a RESTful PHP web service using Lithium which contains comments, each
We have created RESTful web services using Spring's REST support. We need to call
I have a simple RESTful web service that print Hello World ! I'm using
I have succesfully implemented a RESTful Web Service using the .NET 4.0 framework with
I have created Restful web service in jomsocial environment. It's on the local machine.
I have a WCF web service that implements a RESTful interface. We're using the
I have created two separate web applications as well as a Restful API Server.
I have a REStful WCF web service (using a substantially modified WCF Rest Starter
I have created a jax-rs restful service using cxf and annotated my scala service
We have created a WCF RESTful service for a WPF(UI) Application. The UI sends

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.