gpt4 book ai didi

c# - PostAsJsonAsync 之后 WebApi 方法中的对象为空

转载 作者:行者123 更新时间:2023-12-05 00:41:15 24 4
gpt4 key购买 nike

我将一个对象发布到 WebApi 方法。我正在使用 PostAsJsonAsync 来执行此操作。

public async Task<HttpResponseMessage> PostAsync(string token, ServiceCall call)
{
var client = new HttpClient();
client.SetBearerToken(token);

var response = await client.PostAsJsonAsync(Uri + "id/nestedcall", call);

return response;
}

我传递的对象 call 在发布时不为空。

[HttpPost]
[Route("id/nestedcall")]
public async Task<IHttpActionResult> NestedCall([FromBody]ServiceCall call)
{
// call is null here
}

但是在我的 API 方法中它为空。我似乎无法弄清楚为什么我所遵循的所有示例都使用这种格式。

为什么调用对象没有被 web api 拾取?

编辑

这里是 ServiceCall 对象。它位于一个单独的类库中,并且在 Web 应用程序和 API 中都包含一个引用。

public class ServiceCall
{
public ServiceCall(Service service, string grantType)
{
ClientId = service.Id;
ClientSecret = service.Secret;
Uri = service.Uri;
Scope = service.Scope;
GrantType = grantType;
}

public ServiceCall(string clientid, string clientsecret, string uri, string scope, string grantType)
{
ClientId = clientid;
ClientSecret = clientsecret;
Uri = uri;
Scope = scope;
GrantType = grantType;
}

public string ClientId { get; set; }
public string ClientSecret { get; set; }
public string Uri { get; set; }
public string Scope { get; set; }
public string GrantType { get; set; }
}

最佳答案

由于序列化,我在 PostAsJsonAsync 之后在 WebApi 方法中看到了 Object null。最好使用 PostAsync,如下所示:

        var obj = new MyClass()
{
MyProperty = 11
};

using (var client = new HttpClient())
{
string inputJson = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
HttpContent inputContent = new StringContent(inputJson, Encoding.UTF8, "application/json");
HttpResponseMessage response1 = client.PostAsync("http://localhost:60909/api/home/Test", inputContent).Result;
if (response1.IsSuccessStatusCode)
{

}
}

关于c# - PostAsJsonAsync 之后 WebApi 方法中的对象为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37818405/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com