gpt4 book ai didi

c# - HttpClient 通过 BSON 到 RESTful API

转载 作者:太空宇宙 更新时间:2023-11-03 14:38:56 25 4
gpt4 key购买 nike

我已经尝试将对象从窗口客户端发送到 Controller 。

它可以接收测试对象,但idid20null 值。

我是否遗漏了一些配置?

public class Test
{
public int id { get; set; }
public string id2 { get; set; }
}

//webapi配置

public static void Register(HttpConfiguration config)
{

config.MapHttpAttributeRoutes();
config.Formatters.Add(new BsonMediaTypeFormatter());
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}

窗口客户端

private async void Form1_LoadAsync(object sender, EventArgs e)
{
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:58716/");

// Set the Accept header for BSON.
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/bson"));

var aa = new Test()
{
id = 2,
id2="3333"
};

// POST using the BSON formatter.
MediaTypeFormatter bsonFormatter = new BsonMediaTypeFormatter();
var result = await client.PostAsync("Report/Test", aa, bsonFormatter);
result.EnsureSuccessStatusCode();
}

}

网络服务器

public class ReportController : Controller
{
public void Test(Test aa)
{

}
}

最佳答案

Register 正在为 ApiController 配置,而显示的 ReportController 是 MVC Controller

更新目标 Controller 以派生自正确的类型并具有必要的属性。

[RoutePrefix("api/Report")]
public class ReportController : ApiController {
//POST api/Report/Test
[HttpPost]
[Route("Test")]
public IHttpActionResult Test([FromBody]Test model) {
if(ModelState.IsValid) {
//...

return Ok();
}
return BasRequest(ModelState);
}
}

并更新客户端以发送到正确的 URL

//...

// POST using the BSON formatter.
MediaTypeFormatter bsonFormatter = new BsonMediaTypeFormatter();
var result = await client.PostAsync("api/Report/Test", aa, bsonFormatter);
result.EnsureSuccessStatusCode();

关于c# - HttpClient 通过 BSON 到 RESTful API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58490233/

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