Luke
Luke

Reputation: 47

Grab a property of a Delete HttpResponseMessage

I am looking to test the output of one of my API requests below.

async Task DeleteNonExistantFoo()
{
    using (HttpClient client = new HttpClient())
    {
        client.BaseAddress = new Uri("Http://localhost:43240/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        using (HttpResponseMessage response = await client.DeleteAsync("api/foos/1"))
        {
            var responseContent = await response.Content.ReadAsStringAsync();
            //Assert.AreEqual(?????, "A Foo with ID of 1 does not exist.");
        }
    }
}

I want to grab the exceptionMessage from the response below, which is given as a response when I send a DELETE request to the API. When debugging in visual studio it won't let me look at the response content object, giving me the error

"responseContent Cannot obtain value of the local variable or argument because it is not available at this instruction pointer, possibly because it has been optimized away. "

Do I need to convert it to a JSON object to read it?

{
    "message": "An error has occurred.",
    "exceptionMessage": "A Foo with ID of 1 does not exist.",
    "exceptionType": "System.Exception",
    "stackTrace": "
} 

Upvotes: 3

Views: 305

Answers (1)

D-Shih
D-Shih

Reputation: 46249

You can try to use Newtonsoft.Json of JsonConvert.DeserializeObject method to read response Json translate to an object and use it.

create a class ApiResponeMoedl

public class ApiResponeMoedl
{
    public string message { get; set; }
    public string exceptionMessage { get; set; }
    public string exceptionType { get; set; }
    public string stackTrace { get; set; }
}

then using JsonConvert.DeserializeObject<ApiResponeMoedl> deserialize your json data to an ApiResponeMoedl object, then use object's exceptionMessage property you will get your desert information.

async Task DeleteNonExistantRedirect()
{
    using (HttpClient client = new HttpClient())
    {
        client.BaseAddress = new Uri("Http://localhost:43240/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        using (HttpResponseMessage response = await client.DeleteAsync("api/foos/1"))
        {
            var responseContent = await response.Content.ReadAsStringAsync();
            var respOjb = JsonConvert.DeserializeObject<ApiResponeMoedl>(responseContent);
            //respOjb.exceptionMessage
        }
    }
}

Upvotes: 3

Related Questions