Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 没有MediaTypeFormatter可用于读取类型为';字符串';来自媒体类型为';文本/纯文本';_C#_.net_Asp.net Mvc_Json_Httpclient - Fatal编程技术网

C# 没有MediaTypeFormatter可用于读取类型为';字符串';来自媒体类型为';文本/纯文本';

C# 没有MediaTypeFormatter可用于读取类型为';字符串';来自媒体类型为';文本/纯文本';,c#,.net,asp.net-mvc,json,httpclient,C#,.net,Asp.net Mvc,Json,Httpclient,情况就是这样: 他们是中的外部Web服务,我想在ASP.NET MVC应用程序中使用此服务 使用此代码,我尝试从服务获取数据: HttpResponseMessage resp = client.GetAsync("http://localhost:8080/servoy-service/iTechWebService/axws/shop/_authenticate/mp/112818142456/82cf1988197027955a679467c309274c4b").Re

情况就是这样:

他们是中的外部Web服务,我想在ASP.NET MVC应用程序中使用此服务

使用此代码,我尝试从服务获取数据:

HttpResponseMessage resp = client.GetAsync("http://localhost:8080/servoy-service/iTechWebService/axws/shop/_authenticate/mp/112818142456/82cf1988197027955a679467c309274c4b").Result;
resp.EnsureSuccessStatusCode();

var foo = resp.Content.ReadAsAsync<string>().Result;
httpresponsemessageresp=client.GetAsync(“http://localhost:8080/servoy-service/iTechWebService/axws/shop/_authenticate/mp/112818142456/82cf1988197027955a679467c309274c4b”)。结果;
resp.EnsuccessStatusCode();
var foo=resp.Content.ReadAsAsync().Result;
但是,当我运行应用程序时,会出现下一个错误:

没有MediaTypeFormatter可用于读取“String”类型的对象 来自媒体类型为“文本/普通”的内容

如果我打开Fiddler并运行相同的url,我会看到正确的数据,但内容类型是text/plain。然而,我在Fiddler中也看到了我想要的JSON

是否有可能在客户端解决这个问题,还是通过Servoy Web服务

更新:

使用了HttpWebRequest而不是HttpResponseMessage,并使用StreamReader读取响应…

尝试改用ReadAsStringAsync()

ReadAsAsync()
不起作用的原因是
readasync
将尝试使用默认的
MediaTypeFormatter
(即
JsonMediaTypeFormatter
XmlMediaTypeFormatter
,…)之一来读取
text/plain
内容类型的内容。但是,任何默认格式化程序都无法读取
文本/普通
(它们只能读取
应用程序/json
应用程序/xml
等)


通过使用
ReadAsStringAsync()
,无论内容类型如何,内容都将被读取为字符串。

或者您可以创建自己的
MediaTypeFormatter
。我将其用于
text/html
。如果您在其中添加
text/plain
,它也会对您起作用:

public class TextMediaTypeFormatter : MediaTypeFormatter
{
    public TextMediaTypeFormatter()
    {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
    }

    public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
    {
        return ReadFromStreamAsync(type, readStream, content, formatterLogger, CancellationToken.None);
    }

    public override async Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger, CancellationToken cancellationToken)
    {
        using (var streamReader = new StreamReader(readStream))
        {
            return await streamReader.ReadToEndAsync();
        }
    }

    public override bool CanReadType(Type type)
    {
        return type == typeof(string);
    }

    public override bool CanWriteType(Type type)
    {
        return false;
    }
}
公共类TextMediaTypeFormatter:MediaTypeFormatter
{
公共文本MediaTypeFormatter()
{
添加(新的MediaTypeHeaderValue(“text/html”);
}
公共重写任务ReadFromStreamAsync(类型类型、流readStream、HttpContent内容、IFormatterLogger formatterLogger)
{
返回ReadFromStreamAsync(类型、readStream、内容、formatterLogger、CancellationToken.None);
}
公共重写异步任务ReadFromStreamAsync(类型类型、流readStream、HttpContent内容、IFormatterLogger formatterLogger、CancellationToken CancellationToken)
{
使用(var streamReader=newstreamreader(readStream))
{
返回wait wait streamReader.ReadToEndAsync();
}
}
公共覆盖布尔CanReadType(类型)
{
返回类型==typeof(字符串);
}
公共重写bool CanWriteType(类型)
{
返回false;
}
}

最后,您必须将其分配给
HttpMethodContext.responseformter
属性。

我知道这是一个较老的问题,但我觉得来自的答案引导我找到了最佳路径,并希望与大家分享。您甚至不需要实现所有格式化程序的方法。我对使用的api返回的内容类型“application/vnd.api+json”执行了以下操作:

public class VndApiJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
    public VndApiJsonMediaTypeFormatter()
    {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/vnd.api+json"));
    }
}
可以简单地如下所示使用:

HttpClient httpClient = new HttpClient("http://api.someaddress.com/");
HttpResponseMessage response = await httpClient.GetAsync("person");

List<System.Net.Http.Formatting.MediaTypeFormatter> formatters = new List<System.Net.Http.Formatting.MediaTypeFormatter>();
formatters.Add(new System.Net.Http.Formatting.JsonMediaTypeFormatter());
formatters.Add(new VndApiJsonMediaTypeFormatter());

var responseObject = await response.Content.ReadAsAsync<Person>(formatters);
HttpClient-HttpClient=新的HttpClient(“http://api.someaddress.com/");
HttpResponseMessage response=等待httpClient.GetAsync(“person”);
列表格式化程序=新列表();
Add(new System.Net.Http.Formatting.JsonMediaTypeFormatter());
添加(新的VndApiJsonMediaTypeFormatter());
var responseObject=wait response.Content.ReadAsAsync(格式化程序);

超级简单,工作完全符合我的预期。

我遇到了同样的问题,除了错误消息是“没有MediaTypeFormatter可以从媒体类型为“text/html”的内容中读取类型为“Int32”的对象。”
Int32有类似的解决方案吗?Quanda:可以使用return JsonConvert.DeserializeObject(resultString);,结果字符串是ReadAsStringAsync()之后的结果,JsonConvert来自Newtonsoft.Json。您可以从NuGet下载此库。这对于可移植库也非常有用,不仅适用于Int32,而且几乎适用于所有类型或类。我从媒体类型为“text/calendar”的内容中得到了类型为“FileStreamResult”的对象的类似问题。我怎样才能解决这个问题?API正在返回iCal(文件流)
HttpClient httpClient = new HttpClient("http://api.someaddress.com/");
HttpResponseMessage response = await httpClient.GetAsync("person");

List<System.Net.Http.Formatting.MediaTypeFormatter> formatters = new List<System.Net.Http.Formatting.MediaTypeFormatter>();
formatters.Add(new System.Net.Http.Formatting.JsonMediaTypeFormatter());
formatters.Add(new VndApiJsonMediaTypeFormatter());

var responseObject = await response.Content.ReadAsAsync<Person>(formatters);