Home > Net >  Simple HttpRequestMessage but not working
Simple HttpRequestMessage but not working

Time:02-10

I'm writing a simple dotnet core API, under search controller which like below :

[HttpGet("order")]    
public async Task <Order> SearchOrder(string ordername, int siteid) {
    return await service.getorder(ordername,siteid)
}

The swagger UI where the path https://devehost/search/order test pretty work, but when I use another client to call this api by below

client = new HttpClient {
    BaseAddress = new Uri("https://devehost")
};

var request = new HttpRequestMessage(HttpMethod.Get, "Search/order")  {
    Content = new FormUrlEncodedContent(
        new List<KeyValuePair<string, string>> {
            new("ordername", "pizza-1"),
            new("siteid", "1"),
       })
};

var response = await client.SendAsync(request);

The status code always return bad request. But the postman is work, can I know the problem inside?

Thank you

CodePudding user response:

For a GET request, the parameters should be sent in the querystring, not the request body.

GET - HTTP | MDN
Note: Sending body/payload in a GET request may cause some existing implementations to reject the request — while not prohibited by the specification, the semantics are undefined.

For .NET Core, you can use the Microsoft.AspNetCore.WebUtilities.QueryHelpers class to append the parameters to the URL:

Dictionary<string, string> parameters = new()
{
    ["ordername"] = "pizza-1",
    ["siteid"] = "1",
};

string url = QueryHelpers.AppendQueryString("Search/order", parameters);
using var request = new HttpRequestMessage(HttpMethod.Get, url);
using var response = await client.SendAsync(request);
  •  Tags:  
  • Related