No MediaTypeFormatter is available to read an object of type 'String' from content with media type 'text/plain'

前端 未结 3 1777
一整个雨季
一整个雨季 2020-12-29 19:08

This is the situation:

Their is a external webservice in Servoy and I want to use this service in a ASP.NET MVC applicatie.

With this code I attempt to get the

3条回答
  •  情深已故
    2020-12-29 20:08

    Or you can just create your own MediaTypeFormatter. I use this for text/html. If you add text/plain to it, it'll work for you too:

    public class TextMediaTypeFormatter : MediaTypeFormatter
    {
        public TextMediaTypeFormatter()
        {
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
        }
    
        public override Task ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            return ReadFromStreamAsync(type, readStream, content, formatterLogger, CancellationToken.None);
        }
    
        public override async Task 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;
        }
    }
    
    
    

    Finally you have to assign this to the HttpMethodContext.ResponseFormatter property.

    提交回复
    热议问题