当前位置: 移动技术网 > IT编程>开发语言>.net > 【ASP.NET Core】从向 Web API 提交纯文本内容谈起

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

2018年09月03日  | 移动技术网IT编程  | 我要评论

苍南县人事局,淘宝开店教程下载,杨中美

前些时日,老周在升级“华南闲肾回收登记平台”时,为了扩展业务,尤其是允许其他开发人员在其他平台向本系统提交有关肾的介绍资料,于是就为该系统增加了几个 web api。

其中,有关肾的介绍采用纯文本方式提交,大概的代码是这样的。

    [route("api/[controller]/[action]")]
    public class pigcontroller : controller
    {
        [httppost]
        public string kidneyremarks([frombody]string remarks)
        {
            return $"根据你的描述,贵肾的当前状态为:{remarks}";
        }
    }

这个 action 很简单(主要为了方便别人看懂),参数接受一个字符串实例,返回的也是字符串。哦,重点要记住,对参数要加上 frombody 特性。嗯,为啥呢。因为我们要得到的数据是从客户端发来的 http 正文提取的,应用这个特性就是说参数的值来自于提交的正文,而不是 header,也不是 url 参数。

随后老周兴高采烈地用 postman 进行测试。

幻想总是很美丽的,现实总是很骨感的。结果……

 

没成功,这时候,按照常规思路,会产生各种怀疑。怀疑地址错了吗?哪个配置没写上?是不是路由不正确?……

别急,看看服务器返回的状态码:415 unsupported media type。啥意思呢,其实,这就是问题所在了。我们提交纯文本类型的数据,用的 content-type 是 text/plain,可是,不受支持!

不信?现在把提交的内容改为 json 看看。

看看,我没说错吧。

这就很明了啦,json 默认是被支持的,但是纯文本不行。有办法让它支持 text / plain 类型的数据吗?答案是:能的。

在 startup 中使用 configureservices 方法配置服务时,我们一般就是简单地写上。

   services.addmvc();

然后,各个 mvc 选项保持默认。

在 mvc 选项中,可以控制输入和输出的格式,分别由两个属性来管理:

inputformatters 属性:是一个集合,里面的每个对象都要实现 iinputformatter 接口,默认提供对 json 和 xml 的支持。

outputformatters 属性:也是一个集合,里面的元素都要实现 ioutputformatter 接口,默认支持 json 和 xml,也支持文本类型。

也就是说,输出是支持纯文本的,所以 action 可以返回 string 类型的值,但输入是不支持文本格式的,所以,用 text / plain 格式提交,就会得到 415 代码了。

 

明白了这个原理,解决起问题来就好办了,咱们自己实现一个支持纯文本格式的 inputformatter 就行了。不过呢,我们也不必直接实现 iinputformatter 接口,因为,有个抽象类挺好使的—— textinputformatter,处理文本直接实现它就好了。

于是乎,老周就写了这个类。

    public sealed class plaintextinputformatter : textinputformatter
    {
        public override async task<inputformatterresult> readrequestbodyasync(inputformattercontext context, encoding encoding)
        {
            string content;
            using(var reader = context.readerfactory(context.httpcontext.request.body, encoding))
            {
                content = await reader.readtoendasync();
            }
            // 最后一步别忘了
            return await inputformatterresult.successasync(content);
        }
    }

textinputformatter 类只有 readrequestbodyasync 方法是抽象的,所以,如果没其他活要干的话,只实现这个方法就够了。这个方法的功能就是读取 http 请求的正文,然后把你读取到的内容填充给 inputformatterresult 对象。

inputformatterresult 类很有意思的,没有公共构造函数,你无法 new 对象,只能靠媒人介绍对象,通过 failure、success 这些方法直接返回对象实例。这些方法你看名字就知道什么用途了,不用多解释。

在上面代码中,readerfactory 属性其实是个委托,通过构造函数创建的,不过,这个委托实例在传进 readrequestbodyasync 方法时已经创建,你只需要像调用方法一样调用它就行了,第一个参数是一个流,哪里的流?当然是 http 请求的正文了,这里可以透过 httpcontext 的 request 的 body 来获得;第二个参数嘛,呵呵,是文本编码,这个好办,直接把传进 readrequestbodyasync 方法的 encoding 传过去就行了。

readerfactory 委托调用后返回一个 textreader,是了,我们就是用它来读取请求正文的。最后把读出来的字符串填充给 inputformatterresult 就行了。

不过呢,这个类现在还不能用,因为默认情况下,supportedmediatypes 集合是空的,你得添加一下,它支持哪些 content-type,我们这里只要 text / plain 就行了。

        public plaintextinputformatter()
        {
            supportedmediatypes.add("text/plain");
            supportedencodings.add(system.text.encoding.utf8);
        }

这些写在构造函数里就 ok 了。注意 supportedencodings 集合,是配置字符编码,一般嘛,utf-8 最合适了。你也可以从 textinputformatter 类的两个只读的静态字段中获取。

protected static readonly encoding utf8encodingwithoutbom;
protected static readonly encoding utf16encodinglittleendian;

现在基本可以用了。因为我们上面写的那个 action 是带字符串类型参数的,如果你觉得不放心,可以覆写一下 canreadtype 方法,这个方法有个 type 参数,指的是 model type,说白了就是 action 要接收的参数的类型,咱们这里是 string,所以,实现这个方法很简单,如果是字符串类型就返回 true,表示能读取,否则返回 false,表示不能读。

 

回到 startup 类,找到 configureservices 方法,我们在 addmvc 的时候要对 options 配置一下,把咱们刚刚写好的 inputformatter 加进去。

        public void configureservices(iservicecollection services)
        {
            services.addmvc(opt =>
            {
                opt.inputformatters.add(new plaintextinputformatter());
            });
        }

好了,现在再请 postman 大叔,重新测试一下。

 

嗯,皆大欢喜,又解决一个问题了。

 

我们不妨继续扩展一下,如果提交的是 text / plain 数据内容,而 action 想让其赋值给 datetime 或者 int 类型的参数呢。其实也一样,就是自己实现一下输入格式。这一次我们不继承 textinputformatter 类了,而是继承抽象程度更高的 inputformatter 类。

    public sealed class custinputformatter : inputformatter
    {
        public custinputformatter()
        {
            supportedmediatypes.add("text/plain");
        }

        protected override bool canreadtype(type type)
        {
            return (type == typeof(datetime)) || (type == typeof(int));
        }

        public override async task<inputformatterresult> readrequestbodyasync(inputformattercontext context)
        {
            string val;
            using (var reader = context.readerfactory(context.httpcontext.request.body, encoding.utf8))
            {
                val = await reader.readtoendasync();
            }
            inputformatterresult result = null;
            if(context.modeltype == typeof(datetime))
            {
                result = inputformatterresult.success(datetime.parse(val));
            }
            else
            {
                result = inputformatterresult.success(int.parse(val));
            }
            return result;
        }
    }

这一次应该不用我解释,你都能看懂了。不过注意一点,因为要应用的目标参数可能是 int 和 datetime 类型,所以,在填充 inputformatterresult 对象时,你要先检查一下 modeltype 属性。

            if(context.modeltype == typeof(datetime))
            {
                result = inputformatterresult.success(datetime.parse(val));
            }
            else
            {
                result = inputformatterresult.success(int.parse(val));
            }

现在应用一下这个输入格式类。

        public void configureservices(iservicecollection services)
        {
            services.addmvc(o =>
            {
                o.inputformatters.add(new custinputformatter());
            });
        }

 

下面来试试吧,建一个 controller,然后定义两个 action,一个接收 int 类型的参数,一个接收 datetime 类型的参数。

    [route("[controller]/[action]")]
    public class testcontroller : controller
    {
        [httppost]
        public string upload([frombody]datetime dt)
        {
            return $"你提交的时间是:{dt}";
        }

        [httppost]
        public string uploadint([frombody]int val)
        {
            return $"你提交的整数值是:{val}";
        }
    }

frombody 特性千万要记得用上,不然待会读不了你又要到处 debug 了。

 

好,测试开始了,首先试一下 datetime 类型的。

 

再试一下 int 类型的。

 

感觉如何,好刺激吧。好啦,今天的高大上技巧就分享到这儿了。

示例源代码下载:请用洪荒之力猛点这里

 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网