0

I want to send an object via HttpResponseMessage from my client side code and read that object on the server side and save userId alongside.

My client side looks like this:

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");
}

and on the server-side, it should look something like these

[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);
}

I don't know what should I put in that comment section to get the object and then deserialize it?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • I don't see where you are telling the server to expect JSON. Perhaps have a look at this [Send JSON via POST in C# and Receive the JSON returned?](https://stackoverflow.com/questions/23585919/send-json-via-post-in-c-sharp-and-receive-the-json-returned) – Barns May 13 '20 at 13:11

1 Answers1

1

In your client set the content type json:

HttpContent httpContent = new StringContent(json, Encoding.UTF8,"application/json"); 

And your 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);
}

Actually you don't need to separately pass userId - why not set car.UserId on the client side since you already know what value it is (or even better, to set it server side) ? That way you can just pass car in the request body.

auburg
  • 1,373
  • 2
  • 12
  • 22