数据模型未显示在HttpResponseMessage中 [英] Data models not showing up in HttpResponseMessage

查看:127
本文介绍了数据模型未显示在HttpResponseMessage中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从.NET Core MVC应用程序进行简单的API调用:

 使用(var client = new HttpClient())
{
client.BaseAddress = new Uri( http:// localhost:49897);

var response = client.GetAsync( some-route)。Result;
var dataString = response.Content.ReadAsStringAsync()。Result; //此处的数据异常。见下文。

[...] //反序列化dataString
}

client.GetAsync(route)成功命中了API操作方法,该方法最终完成了此操作:

  public HttpResponseMessage Get([FromUri] BindingModel bindingModel)
{
List< SomeModel> resultObjects;

[...] //用数据

填充resultObjects Request.CreateResponse(HttpStatusCode.OK,resultObjects,new JsonMediaTypeFormatter());
}

dataString 结尾等于:

  {\ version\:{\ major\:1,\ \ minor\:1,\ build\:-1,\ revision\:-1,\ majorRevision\:-1,\ minorRevision\: -1},\ content\:{\ objectType\:\ System.Object,System.Private.CoreLib,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = 7cec85d7bea7798e\ ,\ formatter\:{\ indent\:false,\ serializerSettings\:{\ referenceLoopHandling\:0,\ missingMemberHandling\:0,\ \ objectCreationHandling\:0,\ nullValueHandling\:0,\ defaultValueHandling\:0,\转换器\:[],\ preserveReferencesHandling\:0, \ typeNameHandling\:0,\ metadataPropertyHandling\:0,\ typeNameAssemblyFormat\:0,\ typeNameAssemblyFormatHandling\:0,\ constructorHandling\:0, \ contractResolver\:null,\ equalityComparer\:null,\ referenceResolver\:null,\ referenceResolverProvider\:null,\ traceWriter\:null, b binder\:空,\ serializationBinder\:空, \ error\:null,\ context\:{},\ dateFormatString\:\ yyyy'-'MM'-'dd'T'HH':'mm' :'ss.FFFFFFFK\,\ maxDepth\:null,\格式化\:0,\ dateFormatHandling\:0,\ dateTimeZoneHandling\:3,\ \ dateParseHandling\:1,\ floatFormatHandling\:0,\ floatParseHandling\:0,\ stringEscapeHandling\:0,\ culture\:{}} }}} 

或者,以JSON格式:

  {
版本:{
大写:1,
小写:1,
[...]
},
内容:{
objectType: System.Object,System.Private.CoreLib,版本= 4.0.0.0,Culture = neutral,PublicKeyToken = 7cec85d7bea7798e
格式程序:{
缩进:false,
序列化器设置:{
[...]
}
}
}
}

我的模型列表根本不存在。



确切是什么被退回,为什么我的列表中没有模型回应?我查看了一些在线资源,并且似乎按照它们显示的方式进行操作。这是一个相当不错的API调用,所以我不确定发生了什么。

解决方案


确切返回的是什么,为什么我的响应列表中没有模型?


返回的是 HttpResponseMessage 的JSON序列化版本,因为虽然Web API 2特别处理了这种类型,但 ASP.NET Core Web API却不

准确地说, ASP.NET Core Web API支持返回以下类型




  • IActionResult

  • ActionResult< T>

  • <任何其他类型>



前两个经过特殊处理,但是该类型的第三个结果是JSON序列化并返回的,与您看到了。



相反, Web API 2支持以下特殊返回类型




  • void

  • HttpResponseMessage

  • IHttpActionResult

  • <其他type>



正确的解决方案是更新代码以使用自定义的 IActionResult 实现,而不是返回原始的 HttpResponseMessage s。 您可能会发现本指南可以帮助您-在特别是, Microsoft.AspNetCore.Mvc.WebApiCompatShim NuGet软件包具有一个 ResponseMessageResult类,可用于转换您的Web API控制器的方法如下:

  public HttpResponseMessage Foo(Bar quux)
{
返回新的BazHttpResponseMessage();
}

为此:



< Pre class = lang-cs prettyprint-override> public IActionResult Foo(Bar quux)
{
return new ResponseMessageResult(new BazHttpResponseMessage());
}

这应允许您当前的代码按原样工作。


I'm trying to make a simple API call from a .NET Core MVC application:

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri("http://localhost:49897");

    var response = client.GetAsync("some-route").Result;
    var dataString = response.Content.ReadAsStringAsync().Result; // Unexpected data here. See below.

    [...] // deserialize dataString
}

client.GetAsync(route) successfully hits an API action method, which ultimately does this:

public HttpResponseMessage Get([FromUri] BindingModel bindingModel)
{
    List<SomeModel> resultObjects;

    [...] // populate resultObjects with data

    return Request.CreateResponse(HttpStatusCode.OK, resultObjects, new JsonMediaTypeFormatter());
}

But dataString ends up equaling this:

"{\"version\":{\"major\":1,\"minor\":1,\"build\":-1,\"revision\":-1,\"majorRevision\":-1,\"minorRevision\":-1},\"content\":{\"objectType\":\"System.Object, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e\",\"formatter\":{\"indent\":false,\"serializerSettings\":{\"referenceLoopHandling\":0,\"missingMemberHandling\":0,\"objectCreationHandling\":0,\"nullValueHandling\":0,\"defaultValueHandling\":0,\"converters\":[],\"preserveReferencesHandling\":0,\"typeNameHandling\":0,\"metadataPropertyHandling\":0,\"typeNameAssemblyFormat\":0,\"typeNameAssemblyFormatHandling\":0,\"constructorHandling\":0,\"contractResolver\":null,\"equalityComparer\":null,\"referenceResolver\":null,\"referenceResolverProvider\":null,\"traceWriter\":null,\"binder\":null,\"serializationBinder\":null,\"error\":null,\"context\":{},\"dateFormatString\":\"yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK\",\"maxDepth\":null,\"formatting\":0,\"dateFormatHandling\":0,\"dateTimeZoneHandling\":3,\"dateParseHandling\":1,\"floatFormatHandling\":0,\"floatParseHandling\":0,\"stringEscapeHandling\":0,\"culture\":{}}}}}"

Or, in JSON format:

{
    version: {
        major: 1,
        minor: 1,
        [...]
    },
    content: {
        objectType: "System.Object, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"
        formatter: {
            indent: false,
            serializerSettings: {
                [...]
            }
        }
    }
}

My list of models isn't in there at all.

What exactly is being returned, and why isn't my list of models in the response? I've looked at several online resources, and I seem to be doing things the same way as they show. This is a pretty bread-and-butter API call, so I'm not sure what's going on.

解决方案

What exactly is being returned, and why isn't my list of models in the response?

What's being returned is a JSON-serialized version of your HttpResponseMessage, because while Web API 2 handles this type specially, ASP.NET Core web API does not.

To be precise, ASP.NET Core web API supports returning the following types:

  • IActionResult
  • ActionResult<T>
  • <any other type>

The first two are treated specially, but the third results in that type being JSON-serialized and returned, exactly as you saw.

In contrast, Web API 2 supports the following special return types:

  • void
  • HttpResponseMessage
  • IHttpActionResult
  • <any other type>

The correct solution is to update your code to use a custom IActionResult implementation instead of returning raw HttpResponseMessages. You may find this guide aids you in doing so - in particular, the Microsoft.AspNetCore.Mvc.WebApiCompatShim NuGet package has a ResponseMessageResult class that allows you to convert your Web API controller method from this:

public HttpResponseMessage Foo(Bar quux)
{
    return new BazHttpResponseMessage();
}

to this:

public IActionResult Foo(Bar quux)
{
    return new ResponseMessageResult(new BazHttpResponseMessage());
}

which should allow your current code to work as-is.

这篇关于数据模型未显示在HttpResponseMessage中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆