简体   繁体   中英

how to POST query string parameters in URL

C# code below (they say this code works) produces HTTP request that passes parameters in Body. Web server I'm working with doesn't see these params - but it works when POST request contains params in URL like this:

http://my.zadarma.com/auth/?p=%2Fconnect%2Fsms%2F

The C# code below creates following request putting params in the body :

C#:
POST http://my.zadarma.com/auth/ HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: my.zadarma.com
Content-Length: 21
Expect: 100-continue
Connection: Keep-Alive

p=%2Fconnect%2Fsms%2F

Postman creates following request - putting params in URL (my server prefer this):

POST http://my.zadarma.com/auth/?p=%2Fconnect%2Fsms%2F HTTP/1.1
User-Agent: PostmanRuntime/7.29.2
Accept: */*
Postman-Token: d6b3df55-d42f-45e8-82b8-a3fd11b02e35
Host: my.zadarma.com
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Length: 0

How to change following code (using FormUrlEncodedContent or similar) to connect the query string params to URL in POST request? (like Postman does):

public static async Task<HttpStatusCode> UpdateProductAsync()
{
    var url = "http://my.zadarma.com/auth/";

    var client = new System.Net.Http.HttpClient();

    var data = new Dictionary<string, string>
    {
        {"p", "/connect/sms/"}
    };

    var res = await client.PostAsync(url, new FormUrlEncodedContent(data));

    var content = await res.Content.ReadAsStringAsync();
    Console.WriteLine(content);

    var responseString = await res.Content.ReadAsStringAsync();
    return res.StatusCode;

}

I can concatenate URL and params - it will work but I try to avoid concatenation. Updated: Following works. But is there more consistent way to handle params?

        public static async Task<HttpStatusCode> UpdateProductAsync(NetworkParameters networkParameters)
        {
            var url = "http://127.0.0.1:5001/api/v0/files/stat";

            var client = new System.Net.Http.HttpClient();

            string queryStringKey = HttpUtility.UrlEncode("arg", Encoding.UTF8);
            string queryStringValue = HttpUtility.UrlEncode("/KeySet", Encoding.UTF8);

            var res = await client.PostAsync(url + "?" + queryStringKey + "=" + queryStringValue, null);

            var content = await res.Content.ReadAsStringAsync();

            var responseString = await res.Content.ReadAsStringAsync();
            return res.StatusCode;
        }

You can use the queryhelper class from Microsoft.AspNetCore.WebUtilities.dll
https://learn.microsoft.com/en-us/do.net/api/microsoft.as.netcore.webutilities.queryhelpers.addquerystring?view=as.netcore-7.0

var newUrl = QueryHelpers.AddQueryString(url, data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM