HttpRequest消息 POST

And*_*ewE 10 c# post httprequest

我正在尝试通过HttpResponseMessage发送json “样式”字符串。 我创建了以下方法,希望能够成功发送响应消息。

class Foo
{
    /// <summary>
    /// Vendors
    /// </summary>
    public enum Vendor
    {
        [Description("https://someSite.com")]
        FOO = 0x001
    }

    /// <summary>
    /// Send a POST response
    /// </summary>
    /// <param name="vendor"></param>
    /// <param name="data"></param>
    public static async void SendResponseAsync(Vendor vendor, string data)
    {
        Task task = Task.Run(async () =>
        {
            using (var httpClient = new HttpClient())
            using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, vendor.EnumDescriptionToString()))
            {
                var json = Newtonsoft.Json.JsonConvert.DeserializeObject(data);
                httpRequestMessage.Content = new StringContent(json.ToString(), Encoding.UTF8, "application/json");
                var result = await httpClient.SendAsync(httpRequestMessage);
                Console.WriteLine(result.ReasonPhrase);
            }
        });
        await task;
    }
}
Run Code Online (Sandbox Code Playgroud)

我用以下内容来称呼它;

static void Main()
{
    string jsonText = "{\"apikey\": \"someAPIkey\",\"type\": \"ItemRegistered\",   \"order\": \"999999\",   \"item\": \"99999\",    \"datetime\": \"2018-10-12 01:27:11 GMT\"}";
    Foo.SendResponseAsync(Foo.Vendor.FOO, jsonText);
    Console.ReadKey();
}
Run Code Online (Sandbox Code Playgroud)

我收到的错误是400现在你可以说那是我的问题,事实上你是对的,但是,

我想知道为什么当我使用PostMan时我收到一个错误,显示订单号不被认可?以 json 格式,

所以我知道订单号不正确,但是,为什么它没有显示在我的控制台应用程序中?我的发帖方法正确吗?

Max*_*ikh 9

您应该将序列化的 json 表示形式传递到 StringContent 中。你的json变量是对象类型,当你调用它时ToString(),它会给你类似类类型的东西。如果你的datajson已经序列化了,直接传递即可。

或者,如果您有一个对象,请像这样传递它:

var content = new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json");
Run Code Online (Sandbox Code Playgroud)