webapi接收text/plain数据(笔记)

新建类TextPlainType,继承InputFormatter。

public class TextPlainType : InputFormatter
    {
        public TextPlainType() {
            SupportedMediaTypes.Add("text/plain");
        }

        protected override bool CanReadType(Type type)
        {
            if (type == typeof(string) || type == typeof(DateTime)) { 
                return true;
            }
            else
            {
                return false;
            }
        }

        public override Task ReadRequestBodyAsync(InputFormatterContext context)
        {
            object result;
            using (var _reader = context.ReaderFactory(context.HttpContext.Request.Body, Encoding.UTF8)) {
                result = _reader.ReadToEndAsync().Result;
            }
            if (context.ModelType == typeof(string)) {
                return InputFormatterResult.SuccessAsync(Convert.ToString(result));
            } else if (context.ModelType == typeof(DateTime)) {
                return InputFormatterResult.SuccessAsync(Convert.ToDateTime(result));
            }
            else
            {
                throw new InvalidOperationException();
            }
        }
    }

Program注册该类

builder.Services.AddControllers(
    opt => opt.InputFormatters.Insert(0,new TextPlainType())
    ) ;

方法

[HttpPost]
        public string Post([FromBody]string name)
        {
            string say = "我是" + name;
            return say;
            
        }

调用结果

webapi接收text/plain数据(笔记)_第1张图片

参考:

【ASP.NET Core】从向 Web API 提交纯文本内容谈起 

你可能感兴趣的:(C#,c#)