ASP.NET核心中的URL编码和解码

wtf*_*512 92 c# asp.net-core-mvc asp.net-core

HttpContext.Current.Server.UrlEncode
Run Code Online (Sandbox Code Playgroud)

它仅适用于.NET Framework.如何在ASP.NET Core项目中编码或解码uri参数?

Set*_*Set 152

  • 对于ASP.NET Core 2.0+,只需添加System.Net命名空间 - WebUtility类作为System.Runtime.Extensionsnuget包的一部分提供,默认情况下在ASP.NET Core项目中引用.

  • 对于以前的版本,添加Microsoft.AspNetCore.WebUtilitiesnuget包.

然后WebUtility课程将为您提供:

public static class WebUtility
{
    public static string UrlDecode(string encodedValue);
    public static string UrlEncode(string value);
}
Run Code Online (Sandbox Code Playgroud)

  • 我没有对SDK 2.0.0+起作用,但是Manuel Alves回答(System.Net.WebUility). (5认同)
  • 用法是:vardecodedUrl = WebUtility.UrlDecode(encodedUrl); (5认同)

Man*_*ves 75

它可以在.Net Core SDK的2.0.0版本中找到System.Net.WebUtility.UrlEncode(参见文档)

  • 对于Net Core 2+,当我使用`System.Net.WebUtility.UrlEncode`时:空格用`+`编码.我使用`Uri.EscapeDataString`来编码`%20`. (8认同)

ttu*_*tes 32

对于ASP.Net Core 2.0+以及如果需要空格来编码为 %20

而不是+;

使用:

 Uri.EscapeDataString(someString);
Run Code Online (Sandbox Code Playgroud)


Jor*_*dan 7

我正在使用重定向,而 UrlEncode 对我不起作用,因为它对整个网址进行编码。我通过使用 UriHelper.Encode 解决了这个问题,如下所示。

UriHelper.Encode

// generate url string...
return Redirect(Microsoft.AspNetCore.Http.Extensions.UriHelper.Encode(new System.Uri(url)));
Run Code Online (Sandbox Code Playgroud)