.net core中使用GB2312编码的问题

 

最近在用.net core写一个爬虫抓取网页上的数据,碰到了网页编码是GBK的页面,抓取的数据都是乱码,当使用Encoding.GetEncoding(“GBK”)的时候抛出了异常:

'GBK' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.
Parameter name: name

当改用GB2312的时候也抛出了同样的异常:

'GB2312' is not a supported encoding name. For information on defining a custom encoding, see the documentation for the Encoding.RegisterProvider method.
Parameter name: name

从异常上来看是不支持GB2312和GBK。而且提到了需要注册EncodingProvider的方法。CodePagesEncodingProvider定义在NuGet包“System.Text.Encoding.CodePages”之中。所以我们就需要添加System.Text.Encoding.CodePages的依赖。然后在Project.json中添加

{
"dependencies": { "System.Text.Encoding.CodePages": "4.0.1-rc2-24027" }
}

在代码中还需要添加Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);如图:

再次启动就可以可以使用GB2312

posted @ 2017-11-23 12:02  猎美  阅读(9461)  评论(2编辑  收藏  举报