asp.net-web-api – HttpClient不报告从Web API返回的异常
发布时间:2020-05-24 04:19:27 所属栏目:asp.Net 来源:互联网
导读:我正在使用HttpClient来调用我的MVC 4 web api.在我的Web API调用中,它返回一个域对象.如果出现任何问题,将在服务器上抛出HttpResponseException,并显示自定义消息. [System.Web.Http.HttpGet] public Person Person(string loginName) { Person person
|
我正在使用HttpClient来调用我的MVC 4 web api.在我的Web API调用中,它返回一个域对象.如果出现任何问题,将在服务器上抛出HttpResponseException,并显示自定义消息. [System.Web.Http.HttpGet]
public Person Person(string loginName)
{
Person person = _profileRepository.GetPersonByEmail(loginName);
if (person == null)
throw new HttpResponseException(
Request.CreateResponse(HttpStatusCode.NotFound,"Person not found by this id: " + id.ToString()));
return person;
}
我可以使用IE F12在响应正文中看到自定义的错误消息.但是,当我使用HttpClient调用它时,我没有得到自定义的错误消息,只有http代码.对于404,“ReasonPhrase”始终为“Not found”,对于500个代码,“Reason Server Error”为“Internal Server Error”. 有任何想法吗?如何从Web API发回自定义错误消息,同时保持正常的返回类型为我的域对象? 解决方法(把我的答案放在这里以便更好地格式化)是的我看到了它,但HttpResponseMessage没有body属性.我自己想出来了:response.Content.ReadAsStringAsync().Result;.示例代码: public T GetService<T>( string requestUri)
{
HttpResponseMessage response = _client.GetAsync(requestUri).Result;
if( response.IsSuccessStatusCode)
{
return response.Content.ReadAsAsync<T>().Result;
}
else
{
string msg = response.Content.ReadAsStringAsync().Result;
throw new Exception(msg);
}
} (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net-mvc – MVC DB首先修复显示名称
- asp.net – 无法返回JsonResult
- asp.net-core-mvc – ASP NET Core 2.0 appsettings.Develo
- asp.net – asp .net mvc OnResultExecuting modify filter
- asp.net-mvc – 使用ASP.NET MVC测试驱动的开发 – 从哪里开
- 在asp.net中将产品信息存储在购物车中的理想方式
- asp.net-mvc-4 – Razor MVC,在哪里可以通过母版页面,部分视
- asp.net – 从互联网上打开excel文件会打开一个空白的Excel
- asp.net – 递归控制搜索与LINQ
- 简明的ASP.NET验证摘要
推荐文章
站长推荐
- .net – 使用FileStreamResult,MemoryStream是如
- asp.net – .resx vs数据库vs用于提供本地化/全球
- asp.net-mvc-3 – MVC 3 knockoutjs:在使用Edit
- asp.net – Googlebot导致.NET System.Web.HttpE
- .net – 带有数据绑定控件的“无效的回发或回调参
- asp.net-mvc – 如何在ASP.NET MVC中传递页面的元
- asp.net – Visual Studio的访问修饰符下拉列表选
- razor – ASP.NET MVC 4 – for循环帖子模型集合
- 如何从asp.net中的javascript调用codebehind函数
- asp.net – 问题检查后面的代码中的单选按钮
热点阅读
