C# 如何创建可以接收对象的[HttpPost]?
我想通过HttpResponseMessage从客户端代码发送一个对象,并在服务器端读取该对象,同时保存用户ID 我的客户端如下所示:C# 如何创建可以接收对象的[HttpPost]?,c#,rest,http-post,server-side,httpresponsemessage,C#,Rest,Http Post,Server Side,Httpresponsemessage,我想通过HttpResponseMessage从客户端代码发送一个对象,并在服务器端读取该对象,同时保存用户ID 我的客户端如下所示: public async Task<ViewResult> Add(Car car) { Car c; using (Database db = new Database()) { c = db.Cars.First(x => x.Id == car.Id);
public async Task<ViewResult> Add(Car car)
{
Car c;
using (Database db = new Database())
{
c = db.Cars.First(x => x.Id == car.Id);
}
HttpClient client = new HttpClient();
string json = JsonConvert.SerializeObject(c);
HttpContent httpContent = new StringContent(json);
string url = "https://localhost:5001/api/cars/Saved/userId = " + AccountController.curentUser;
HttpResponseMessage response = await client.PostAsync(url, httpContent);
return View("~/Views/Car/PreviewCar.cshtml");
}
在服务器端,它应该是这样的
[HttpPost("Saved/userId = {userId}")]
public async Task<ActionResult<CarS>> PostSavedCar(string userId)
{
// car = get from client side
car.UserId = userId;
_context.SavedCars.Add(car);
await _context.SaveChangesAsync();
return CreatedAtAction("GetSavedCar", new { id = car.Id }, car);
}
我不知道我应该在注释部分添加什么来获取对象,然后反序列化它?在您的客户端中设置内容类型json:
HttpContent httpContent = new StringContent(json, Encoding.UTF8,"application/json");
以及您的Api:
[HttpPost("Saved/userId = {userId}")]
public async Task<ActionResult<CarS>> PostSavedCar([FromBody]Car car, string userId)
{
car.UserId = userId;
_context.SavedCars.Add(car);
await _context.SaveChangesAsync();
return CreatedAtAction("GetSavedCar", new { id = car.Id }, car);
}
实际上,您不需要单独传递userId,为什么不在客户端设置car.userId呢?因为您已经知道它是什么值,或者更好,可以在服务器端设置它?这样,您就可以在请求正文中传递car。我已经尝试过了,但是如果我在方法中添加了其他参数,我的客户端将返回代码415-“Unsupported Media Type”。我已经编辑了我的答案-您需要将内容类型设置为application/jsonI,但我看不到您在哪里告诉服务器需要JSON。也许你可以看看这个