c# - 如何创建可以接收对象的[HttpPost]?
问题描述
我想通过HttpResponseMessage
我的客户端代码发送一个对象,并在服务器端读取该对象并将 userId 保存在旁边。
我的客户端看起来像这样:
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 。
推荐阅读
- python - 创建模型时的信号
- php - 找不到时如何修复我的代码以重置行
- matlab - 在 matlab 中使用 logig 层而不是 softmax 层创建深度网络
- ruby-on-rails - Rails 5.1+ 路由:`resources` 不起作用,但显式路由定义有效
- java - 使用 Payara 服务器创建 (javax.sql.XADataSource) 数据源 (Microsoft SQLServer) 时出错:java.lang.NoSuchFieldError: isEC
- javascript - HTML 文件在 Django 中无法正确加载
- assembly - 装配几何图
- javascript - 如何在 Zap 代码中初始化 z 对象以使用 z.JSON.parse 函数?
- python - 考虑到具有多个 ID 的最后一条记录的数据的累积和问题
- django - 在 Heroku 上部署 Django 应用程序时没有名为“dj_database_url”的模块