如何创建可以接收对象的[HttpPost]?

问题描述 投票:0回答:1

我想把一个对象通过 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);
}

我不知道应该在那个注释部分写上什么,才能得到对象,然后反序列化?

c# rest http-post server-side httpresponsemessage
1个回答
1
投票

在你的客户端设置内容类型为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了。

© www.soinside.com 2019 - 2024. All rights reserved.