2

I am trying to create a Web API client C# console app to consume a Restful Web API class in Visual Studio. For the client, I am having issues with updating a record. I want to let the user enter an existing record ID number. One record I have in my Product table is:

Manufacturer = "Dell", OperatingSystem = "Windows 10", Name = "AMD A6-Series", Price = 279.99m, ItemsInStock = 600;

Here is the method I have so far:

static async Task RunAsyncUpdateRecord()
{
    Console.Write("Enter Product ID: ");
    string inputID = Console.ReadLine();
    int id;
    if (int.TryParse(inputID, out id))
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:61147/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            HttpResponseMessage response = await client.PutAsync("api/products/" + id);                    if (response.IsSuccessStatusCode)   
            {    
                Console.Write("Success");    
            }    
            else    
            {
                Console.Write("Error");    
            }
        }
    }
    else
    {
        Console.WriteLine("Input is invalid, you must enter an integer for the record number.");
    }
}

I either keep getting the error message from Console.Write("Error"); or nothing happens at all.

Thomas Bormans
  • 5,156
  • 6
  • 34
  • 51
bkostraa
  • 31
  • 2
  • does the app hosting the web api have PUT enabled? See this http://stackoverflow.com/a/10907343/1134076. Might be useful to add the error stack trace too. – Dr Schizo Apr 11 '16 at 09:34
  • Yes, it is enabled – bkostraa Apr 11 '16 at 09:49
  • Having "Error" as an error message isn't very helpful. If I were you I'd write out the response code, for example, "404 Not Found" or "405 Method Not Allowed" and that will help you better understand why your application isn't running as it should – Ian Murray Apr 11 '16 at 09:57
  • What is the HTTP status code returned? Is there an error thrown on the server side? One clear issue is that there is no content set in your request which is likely to cause service or database validation errors on the server. However, with only a string of "Error" to work with it is impossible to know. – strickt01 Apr 11 '16 at 10:53
  • You aren't "PUTting" anything: `await client.PutAsync("api/products/" + id);` needs another parameter of type `HttpContent`, or it will create a request with an empty body. Also, please be more explicit, give us the HTTP response message and show us your server-side code (starting with the controller). – Federico Dipuma Apr 11 '16 at 14:11

0 Answers0