abhi
abhi

Reputation: 3136

BadRequest Message from WebClient

When I make the call via Postman I get a nice message saying "failure in user creation and a 400 Bad Request".

(Screenshot attached).Failure In User Creation

When I run my c# code, it directly jumps to an exception, but the exception message is not the one I see in Postman. Here is my C# code.

 try
        {
            var wc = new WebClient();
            wc.Headers.Add("Content-Type", "application/json");
            wc.BaseAddress = ServiceUrl;
            wc.Encoding = Encoding.UTF8;
            byte[] ret = wc.UploadData($"{ServiceUrl}/api/CreateUser",
                "POST", System.Text.Encoding.UTF8.GetBytes(userjson));
            var resp = System.Text.Encoding.UTF8.GetString(ret);
            Console.WriteLine(resp);
        }
        catch (WebException e)
        {
            Console.WriteLine("This program is expected to throw WebException on successful run."+
                              "\n\nException Message :" + e.Message);
            if(e.Status == WebExceptionStatus.ProtocolError) 
            {
                Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
                Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
                Console.WriteLine("Status Method : {0}", ((HttpWebResponse)e.Response).Method);
            }
        }

The error message I am getting from my code is

Exception Message :The remote server returned an error: (400) Bad Request.

I would like to get this same message in my C# code.

I have already explored the HttpClient in System.Net.Http and that works, but it would involve changing a lot of code in this application. I am slightly reluctant to do that.

Upvotes: 0

Views: 1974

Answers (1)

Aage
Aage

Reputation: 6252

With WebClient you should be able to get the response message like this:

using (WebClient client = new WebClient())
{
    try
    {
        string data = client.DownloadString("https://localhost:44357/weatherforecast");
    }
    catch (WebException ex)
    {
        using (StreamReader r = new StreamReader(ex.Response.GetResponseStream()))
        {
            string response = r.ReadToEnd(); // access the reponse message
        }
    }
}

I've simplified the code (using an HTTP GET) to focus on what you need.

Upvotes: 1

Related Questions