how to post plain text to ASP.NET Web API endpoint?

前端 未结 6 2235
时光取名叫无心
时光取名叫无心 2020-12-04 17:34

I have an ASP.NET Web API endpoint with controller action defined as follows :

[HttpPost]
public HttpResponseMessage Post([FromBody] object text)

6条回答
  •  我在风中等你
    2020-12-04 18:24

    Purified version using of gwenzek's formatter employing async/await:

    public class PlainTextFormatter : MediaTypeFormatter
    {
        public PlainTextFormatter()
        {
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
        }
    
        public override bool CanReadType(Type type) =>
            type == typeof(string);
    
        public override bool CanWriteType(Type type) =>
            type == typeof(string);
    
        public override async Task ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            var streamReader = new StreamReader(readStream);
            return await streamReader.ReadToEndAsync();
        }
    
        public override async Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)
        {
            var streamReader = new StreamWriter(writeStream);
            await streamReader.WriteAsync((string) value);
        }
    }
    
    
    

    Please note I intentionally do not dispose StreamReader/StreamWriter, as this will dispose underlying streams and break Web Api flow.

    To make use of it, register while building HttpConfiguration:

    protected HttpConfiguration CreateHttpConfiguration()
    {
        HttpConfiguration httpConfiguration = new HttpConfiguration();
        ...
        httpConfiguration.Formatters.Add(new PlainTextFormatter());
        ...
        return httpConfiguration;
    }
    

    提交回复
    热议问题