我已经尝试将对象从窗口客户端发布到控制器。
可以接收测试对象,但是id
和id2
是0
和null
值。
我错过了一些配置吗?
public class Test
{
public int id { get; set; }
public string id2 { get; set; }
}
// webapiconfig
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();
}
}
Web服务器
public class ReportController : Controller
{
public void Test(Test aa)
{
}
}
[Register
为ApiController
配置,而显示的ReportController
是MVC 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();