How to build a query string for a URL in C#?

前端 未结 30 3147
借酒劲吻你
借酒劲吻你 2020-11-22 01:55

A common task when calling web resources from a code is building a query string to including all the necessary parameters. While by all means no rocket science, there are so

30条回答
  •  我在风中等你
    2020-11-22 02:20

    Flurl [disclosure: I'm the author] supports building query strings via anonymous objects (among other ways):

    var url = "http://www.some-api.com".SetQueryParams(new
    {
        api_key = ConfigurationManager.AppSettings["SomeApiKey"],
        max_results = 20,
        q = "Don't worry, I'll get encoded!"
    });
    

    The optional Flurl.Http companion lib allows you to do HTTP calls right off the same fluent call chain, extending it into a full-blown REST client:

    T result = await "https://api.mysite.com"
        .AppendPathSegment("person")
        .SetQueryParams(new { ap_key = "my-key" })
        .WithOAuthBearerToken("MyToken")
        .PostJsonAsync(new { first_name = firstName, last_name = lastName })
        .ReceiveJson();
    

    The full package is available on NuGet:

    PM> Install-Package Flurl.Http

    or just the stand-alone URL builder:

    PM> Install-Package Flurl

提交回复
热议问题