Asp.net core 学习笔记 (操作 URL 和 Query)

更新: 2022-04-01

翻新版本: ASP.NET Core – 操作 Uri 和 Query 

 

更新 :2018-7-25

直接添加 query string.

var resetPasswordLink = QueryHelpers.AddQueryString($"{Request.Scheme}://{Request.Host.Value}{forgotPasswordData.resetPasswordUrl}", "token", token);

 

 

refer : https://benjii.me/2017/04/parse-modify-query-strings-asp-net-core/

build-in 的功能哦. 

using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.AspNetCore.WebUtilities;

public IActionResult About()
{
    string currentFullUrl = $"{Request.Scheme}://{Request.Host}{Request.Path}{Request.QueryString}";            
    var uri = new Uri(currentFullUrl);
    var baseUri = uri.GetComponents(UriComponents.Scheme | UriComponents.Host | UriComponents.Port | UriComponents.Path, UriFormat.UriEscaped);
    var query = QueryHelpers.ParseQuery(uri.Query);
    var items = query.SelectMany(x => x.Value, (col, value) => new KeyValuePair<string, string>(col.Key, value)).ToList();
    var pageItem = items.FirstOrDefault(i => i.Key == "page"); // 是可以有多个的哦.
    if (pageItem.Key != null) // 判断是否有 
    {
        int page = Convert.ToInt32(pageItem.Value); 
    }
    items.RemoveAll(x => x.Key == "key");  
    items.RemoveAll(x => x.Key == "key" && x.Value == "value");  
    var qb = new QueryBuilder(items);
    qb.Add("newKey", "newValue");
    var newUrl = baseUri + qb.ToQueryString();
    return View();
}

part 2 

UriBuilder uriBuilder = new UriBuilder();
uriBuilder.Scheme = Request.Scheme;
uriBuilder.Host = Request.Host.Host;
if (Request.Host.Port.HasValue)
{
    uriBuilder.Port = Request.Host.Port.Value;
}
uriBuilder.Path = forgotPasswordData.resetPasswordPath;
var queryBuilder = new QueryBuilder();
queryBuilder.Add("token", token);
uriBuilder.Query = queryBuilder.ToString();
var url = uriBuilder.ToString();

 

 

以上

 

posted @ 2018-05-11 13:02  兴杰  阅读(624)  评论(0编辑  收藏  举报