开发手册 欢迎您!
软件开发者资料库

.NET Core(C#)html和url字符串编解码方法(HtmlDecode、HtmlEncode、UrlDecode、UrlEncode)

本文主要介绍.NET Core(C#)中,封装HtmlDecode、HtmlEncode、UrlDecode、UrlEncode成工具类,并且兼容.NET Framework的方法,以及相关的示例代码。

1、使用UrlEncode和UrlDecode编解码

#if !NETSTANDARDusing System.Web;#elseusing System.Net;#endifusing System;namespace UrlHelper{public class UrlHelper{protected string UrlEncode(string value){var tmp = value;#if !NETSTANDARDreturn HttpUtility.UrlEncode(tmp, System.Text.Encoding.GetEncoding("utf-8"));#elsereturn WebUtility.UrlEncode(tmp);#endif}public static string UrlDecode(string value){var tmp = value;#if !NETSTANDARDreturn HttpUtility.UrlDecode(tmp);#elsereturn WebUtility.UrlDecode(tmp);#endif}}}

2、使用HtmlEncode和HtmlDecode编解码

using System;using System.Net;#if !NETSTANDARDusing System.Web;#else#endifnamespace HtmlHelpler{public class HtmlHelpler{public static string HtmlDecode(string value){var tmp = value;#if !NETSTANDARDreturn HttpUtility.HtmlDecode(tmp);#elsereturn WebUtility.HtmlDecode(tmp);#endif}public static string HtmlEncode(string value){var tmp = value;#if !NETSTANDARDreturn HttpUtility.HtmlEncode(tmp);#elsereturn WebUtility.HtmlEncode(tmp);#endif}}}

相关文档:ASP.NET Core(.NET Core)中使用UrlDecode和UrlEncode方法