asp.net-web-api – HttpClient不报告从Web API返回的异常
发布时间:2020-12-15 23:07:00 所属栏目:asp.Net 来源:网络整理
导读:我正在使用HttpClient来调用我的MVC 4 web api.在我的Web API调用中,它返回一个域对象.如果出现任何问题,将在服务器上抛出HttpResponseException,并显示自定义消息. [System.Web.Http.HttpGet] public Person Person(string loginName) { Person person = _p
我正在使用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 TextBox中的值和文本属性(值被Text覆盖)
- asp.net – SignalR(Hub)可以发送除信号制作者之外的消息吗
- asp.net-mvc – NuGet项目>添加库包参考未出现
- ASP.NET IIS – 请求什么时候排队?
- iis-7.5 – 使用虚拟目录/应用程序在IIS中托管ASP.NET 5 We
- asp.net – 如何在Azure网站上设置machineKey
- asp.net-mvc – 在ASP.NET Identity 2.0中更改AspNetUsers表
- dependency-injection – Ninject:构造函数参数
- asp.net – 在2K3构建服务器上的单元测试中不允许使用’应用
- ASP.NET拒绝基于角色访问某些页面
推荐文章
站长推荐
- asp-classic – 你用什么来编辑和开发经典ASP
- 在ASP.NET应用程序中实现多语言的最佳方式
- 内存数据库技术选型
- asp.net – 是每个用户或每个应用程序的标准Outp
- asp.net-mvc-4 – 在MVC4环境中使用Razor和Angul
- asp.net – 当你不能使用ViewState时你会怎么做?
- asp.net-mvc – 由Url.Action生成的Asp.Net MVC错
- asp.net-mvc – 使用OWIN的Google身份验证Oauth在
- Aspect-Oriented Programming : Aspect-Oriented
- asp.net-mvc-3 – 实体框架插件架构推荐
热点阅读