【问题标题】:HttpClient does not work in asp.net (works in Postman)HttpClient 在 asp.net 中不起作用(在 Postman 中起作用)
【发布时间】:2017-02-21 14:25:57
【问题描述】:

我测试了这段代码,它第一次运行;现在我得到空的回应。但是,使用 Postman,我能够得到响应。似乎没有正确读取 Json。我得到一个 400 错误。

private Guid GetToken()
{
var client = new HttpClient();
var uri = "url";
var jsonInString = JsonConvert.SerializeObject(new Authorization());

var response = client.PutAsync(uri, new StringContent(jsonInString, Encoding.UTF8, "application/json")).Result;
var x = response.Content.ReadAsStringAsync().Result;

if(x=="")
    return Guid.Empty;

return new Guid(response.Content.ReadAsStringAsync().Result);
}

public class Authorization
{
    public string _x;
    public Guid _y;
    public Guid _z;
    public long _a;
    public long _b;

    public Authorization()
    {
        x = 123; //dummy data
        y = xx-xx-xx-xxxxx-xx-xxxx;
        z = xx-xx-xx-xxxxx-xx-xxxx;
        a = 123;
        b = 123;
    }
}

【问题讨论】:

  • Http 代码 400 保留为“错误请求”。这意味着您的应用程序的后端无法处理给定的请求。也许您将方法(Get/Post)与 Postman 和您的实际应用程序混淆了。
  • 会不会是忘记声明传输方式了?
  • 方法是PUT,其实我什么都没改。这是正确的 var response = client.PutAsync(uri, new StringContent(jsonInString, Encoding.UTF8, "application/json")).Result;

标签: json asp.net-core request put


【解决方案1】:

我设法解决了。问题在于Json object 中的属性名称。

我使用了 Resharper 并将 Json object 中的变量从 Id 重命名为 _id(注意下划线)。

【讨论】:

    猜你喜欢
    • 2020-11-15
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-04
    相关资源
    最近更新 更多