如何使用 aspnet 2.0 post 到 API

How to post to an API using aspnet 2.0

订阅的服务使用 api 并在下方提供此示例 php。 我有一个旧的 aspnet 脚本,我想对其进行修改以执行相同的操作,但因为我不是程序员并且很难使用它。我阅读了有关 httpclient 和各种代码的信息,但没有完全满足我的需要。这可以轻松移植吗?谢谢/J

    $client = new \GuzzleHttp\Client();
$response = $client->post("https://api.domain.com/v3/accounts", [
    'headers' => [
            "Authorization" => "Bearer {token}",
            "Accept" => "application/json",
            "Content-Type" => "application/json",
        ],
    'json' => [
            "username" => "eius",
            "password" => "nemo",
        ],
]);
$body = $response->getBody();
print_r(json_decode((string) $body));

urltoken 更改为您需要的正确值,最小代码示例控制台应用程序:

using System;
using System.Net;
using System.IO;
using System.Web.Script.Serialization;

static void Main(string[] args)
{
    var url = "https://postman-echo.com/post";
    var token = "super secret token";
    var httpWR = WebRequest.CreateHttp(url);
    var serializer = new JavaScriptSerializer();
    var result = string.Empty;

    httpWR.Accept = "application/json";
    httpWR.ContentType = "application/json";
    httpWR.Method = "POST";
    httpWR.Headers.Add("Authorization", $"Bearer {token}");

    using (var sw = new StreamWriter(httpWR.GetRequestStream()))
    {
        string json = serializer.Serialize(new
        {
            username = "eius",
            password = "nemo"
        });
        sw.Write(json);
    }

    var response = (HttpWebResponse)httpWR.GetResponse();
    using (var sr = new StreamReader(response.GetResponseStream()))
    {
        result = sr.ReadToEnd();
    }

    Console.WriteLine(result);
}