4

如何在 ASP.NET Core 漂亮的建立 Query String 查詢字串

 2 years ago
source link: https://blog.miniasp.com/post/2022/03/31/Build-Query-String-in-ASPNET-Core
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

我們在建立含有 Query String 的網址時,若是用字串串接的方式來實作,程式碼會相對的比較醜一點。從 ASP.NET Core 1.0 開始,就有好幾個專門用來建立 Query String 的類別,這些類別不但可以提升程式碼的可讀性,所有的 Query String 也都會進行必要的 URL Encode 動作,讓你的網址更符合國際標準,建議可以多加利用。

使用 QueryBuilder 類別

範例程式如下:

var authUrl = "https://access.line.me/oauth2/v2.1/authorize";

var qb = new QueryBuilder();
qb.Add("response_type", "code");
qb.Add("client_id",     config["LINELogin:client_id"]);
qb.Add("redirect_uri",  config["LINELogin:redirect_uri"]);
qb.Add("scope",         config["LINELogin:scope"]);
qb.Add("state",         GenerateNonce());

var url = $"{authUrl}{qb.ToQueryString().Value}";

此類別內建於 Microsoft.AspNetCore.Http.Extensions 套件中。

使用 QueryHelpers 類別

範例程式如下:

var authUrl = "https://access.line.me/oauth2/v2.1/authorize";

var query = new Dictionary<string, string>
{
    ["response_type"] = "code",
    ["client_id"]     = config["LINELogin:client_id"],
    ["state"]         = GenerateNonce(),
    ["scope"]         = config["LINELogin:scope"],
    ["redirect_uri"]  = config["LINELogin:redirect_uri"],
};

var url = QueryHelpers.AddQueryString(authUrl, query);

此類別內建於 Microsoft.AspNetCore.WebUtilities 套件中。

若要用 .NET 解析完整的網址,通常用 Model Binding 就可以做到,但你若真的需要手動解析網址,可以參考以下範例程式:

var authUrl = "https://access.line.me/oauth2/v2.1/authorize?response_type=code&client_id=111111&state=222&scope=profile%20openid%20email&redirect_uri=https%3A%2F%2Flocalhost%3A7133%2Fcallback";

var uri = new Uri(authUrl);

// https://access.line.me/oauth2/v2.1/authorize
var uriPath = uri.GetLeftPart(UriPartial.Path);

// ?response_type=code&client_id=111111&state=222&scope=profile%20openid%20email&redirect_uri=https%3A%2F%2Flocalhost%3A7133%2Fcallback"
var uriQuery = uri.GetLeftPart(UriPartial.Query);
var uriQuery = uri.Query;

// https://
var uriScheme = uri.GetLeftPart(UriPartial.Scheme);

// // https://access.line.me
var uriAuthority = uri.GetLeftPart(UriPartial.Authority);

// using Microsoft.AspNetCore.WebUtilities;
var query = QueryHelpers.ParseQuery(uri.Query);

var client_id = query["client_id"].ToString();

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK