【发布时间】:2021-06-18 05:58:23
【问题描述】:
我是 .NET Framework 的新手,正在为它提供服务。
service.cs
public dynamic GetList(GetList_Request getList_Request)
{
dynamic result = null;
HttpClient httpClient = new HttpClient();
HttpResponseMessage response = null;
var json = JsonConvert.SerializeObject(getList_Request);
var strContent = new StringContent(json, UnicodeEncoding.UTF8, "application/json");
string apiUrl = "http://10.216.447.19:5006";
response = httpClient.PostAsync(apiUrl, strContent).Result;
try
{
if (response.IsSuccessStatusCode)
{
result = response.Content.ReadAsAsync<dynamic>().Result;
}
else
{
throw new Exception("API called failed for POST");
}
}
catch (Exception ex)
{
throw ex;
}
return result;
}
controller.cs
public dynamic GetList(GetList_Request getList_Request)
{
try
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
GetList_Request response = _serv.GetList(getList_Request);
if (response == null)
return NotFound();
return Ok(response);
}
catch (Exception ex)
{
throw new HttpResponseException(ControllerContext.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, logger.Error(ex).ToString()));
}
}
解析结果时出现错误。服务结果为 200 ok,但控制器中出现错误。我该如何解决这个问题?我尝试了多种方法,但都没有成功。
在 service.cs 中 result = response.Content.ReadAsAsync<dynamic>().Result 正在抛出异常
Message = "没有 MediaTypeFormatter 可用于从媒体类型为 'text/html' 的内容中读取类型为 'Object' 的对象。"`
控制器的堆栈跟踪:
STAR.WebAPI.Controllers.xController.GetList(GetList_Request getList_Request)
在
C:\Users\1000277196\Project\Controllers\xController.cs:59 行
在lambda_method(Closure , Object , Object[] )
在System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor. <>c__DisplayClass6_1.b__3(Object instance, Object[] methodParameters)
在System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments)
在System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary'2 arguments, CancellationToken cancellationToken)
【问题讨论】:
-
在您的控制器中,您将
response的类型声明为GetList_Request,这对我来说看起来很可疑。我建议最初将类型更改为dynamic,然后显式执行任何转换或序列化。除此之外,这将有助于提供完整的控制器类 - 堆栈轨道显示“第 59 行”,但那是哪一行?Ok()方法是什么? -
result = response.Content.ReadAsAsync<dynamic>().Result正在抛出异常Message = "No MediaTypeFormatter is available to read an object of type 'Object' from content with media type 'text/html'." -
ReadAsAsync<dynamic>()通常在预期结果是序列化对象(例如(或类似于)JSON)时使用。在这种情况下,响应看起来像是 HTML。尝试用result = response.Content.ReadAsStringAsync();替换该行并检查结果。您将看到的可能不是可以反序列化的东西。 (根据结果以及您想用它做什么,您可能还需要将方法的返回类型更改为string。)
标签: c# asp.net .net dotnet-httpclient