netcore url编码/解码
直接上代码
using Microsoft.AspNetCore.Mvc;
using System.Web;namespace SaaS.OfficialWebSite.Web.Controllers
{public class UrlCodeController : Controller{public IActionResult Index(){return View();}[HttpPost]public IActionResult Encode([FromBody] UrlEncodeRequest request){if (string.IsNullOrWhiteSpace(request.Text)){return BadRequest(new { error = "输入文本不能为空" });}try{string encodedText;if (request.EncodeFullUrl){// 编码整个URLencodedText = request.EncodeSpaceAsPlus? Uri.EscapeUriString(request.Text).Replace("%20", "+"): Uri.EscapeUriString(request.Text);}else{// 仅编码查询部分var uriBuilder = new UriBuilder(request.Text);var query = HttpUtility.ParseQueryString(uriBuilder.Query);if (request.EncodeSpaceAsPlus){uriBuilder.Query = query.ToString().Replace("%20", "+");}encodedText = uriBuilder.Uri.AbsoluteUri;}return Ok(new { encodedText });}catch (Exception ex){return StatusCode(500, new { error = "编码过程中发生错误", details = ex.Message });}}[HttpPost]public IActionResult Decode([FromBody] UrlDecodeRequest request){if (string.IsNullOrWhiteSpace(request.Text)){return BadRequest(new { error = "输入文本不能为空" });}try{// 先替换+号为空格,然后解码var decodedText = Uri.UnescapeDataString(request.Text.Replace("+", " "));return Ok(new { decodedText });}catch (Exception ex){return StatusCode(500, new { error = "解码过程中发生错误", details = ex.Message });}}}public class UrlEncodeRequest{public string Text { get; set; }public bool EncodeFullUrl { get; set; } = true;public bool EncodeSpaceAsPlus { get; set; } = false;}public class UrlDecodeRequest{public string Text { get; set; }}
}
运行效果:url编码/解码