猿问

获取 Delete HttpResponseMessage 的属性

我希望测试下面我的 API 请求之一的输出。


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

        }

    }

}

我想从下面的响应中获取 exceptionMessage,当我向 API 发送 DELETE 请求时,它作为响应给出。在 Visual Studio 中调试时,它不会让我查看响应内容对象,从而出现错误


“responseContent 无法获取局部变量或参数的值,因为它在此指令指针处不可用,可能是因为它已被优化掉。”


我是否需要将其转换为 JSON 对象才能读取它?


{

    "message": "An error has occurred.",

    "exceptionMessage": "A Foo with ID of 1 does not exist.",

    "exceptionType": "System.Exception",

    "stackTrace": "


慕妹3242003
浏览 169回答 1
1回答

幕布斯6054654

你可以尝试使用Newtonsoft.Json的JsonConvert.DeserializeObject方法来读取响应的Json转换成一个对象,并使用它。创建一个类 ApiResponeMoedlpublic class ApiResponeMoedl{&nbsp; &nbsp; public string message { get; set; }&nbsp; &nbsp; public string exceptionMessage { get; set; }&nbsp; &nbsp; public string exceptionType { get; set; }&nbsp; &nbsp; public string stackTrace { get; set; }}然后使用JsonConvert.DeserializeObject<ApiResponeMoedl>将您的 json 数据反序列化为一个ApiResponeMoedl对象,然后使用对象的exceptionMessage属性,您将获得沙漠信息。async Task DeleteNonExistantRedirect(){&nbsp; &nbsp; using (HttpClient client = new HttpClient())&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; client.BaseAddress = new Uri("Http://localhost:43240/");&nbsp; &nbsp; &nbsp; &nbsp; client.DefaultRequestHeaders.Accept.Clear();&nbsp; &nbsp; &nbsp; &nbsp; client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));&nbsp; &nbsp; &nbsp; &nbsp; using (HttpResponseMessage response = await client.DeleteAsync("api/foos/1"))&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var responseContent = await response.Content.ReadAsStringAsync();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var respOjb = JsonConvert.DeserializeObject<ApiResponeMoedl>(responseContent);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //respOjb.exceptionMessage&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
随时随地看视频慕课网APP
我要回答