как перевести js ajax запрос в c#

$.ajax({
      crossDomain: true,
      type: "GET",
      url: "url",
      data: {a:"a",b:"b"},
      dataType: "xml",
    }); 

как оформить объект data в c#?

WebRequest wr = WebRequest.Create(url);
wr.Method = "GET";
wr.Headers["dataType"] = "xml";
wr.Headers["data"] = ?;

пробовал

wr.Headers["data"] = "{a:1234,b:\"b\"}";

ответ Wrong input data


Ответы (1 шт):

Автор решения: aepot

WebRequest устарел еще до того как динозавры вымерли.

Сейчас модно писать нормальный асинхронный код для работы с сетью. А для HTTP запросов использовать HttpClient.

Потом, есть документация $.ajax()

data
Type: PlainObject or String or Array

Data to be sent to the server. If the HTTP method is one that cannot have an > entity body, such as GET, the data is appended to the URL.

Так как у вас запрос GET, то следовательно аргументы надо передавать как параметры урла.

private static readonly HttpClient _client = new HttpClient();

static async Task Main(string[] args)
{
    string url = "https://google.com";

    Dictionary<string, string> queryData = new Dictionary<string, string>()
    {
        ["a"] = 1234.ToString(),
        ["b"] = "b"
    };

    UriBuilder uriBuilder = new UriBuilder(url)
    { 
        Query = new FormUrlEncodedContent(queryData).ReadAsStringAsync().Result
    };
    Console.WriteLine(uriBuilder.Uri);

    string response = await _client.GetStringAsync(uriBuilder.Uri);
    //Console.WriteLine(response);
}

Да, я знаю, что Uri query строится в C# страшновато, но уж что дал Microsoft, то и используем.

https://google.com/?a=1234&b=b

А dataType - это вам вообще не нужно в C#, смотреть в документацию по ссылке выше.

→ Ссылка