0

I am somewhat of a beginner so bear with me. I have an HttpPost-method in an API, that makes use of the CreatedAtAction-method for the http-response:

[HttpPost]
public async Task<ActionResult<RealtorFirm>> AddAsync(RealtorFirmPostDTO realtorFirmPostDTO)
{
    if (realtorFirmPostDTO == null)
    {
        return BadRequest();
    }
    // Map DTO to entity
    RealtorFirm realtorFirm = await _realtorFirmRepository.AddAsync(_mapper.Map<RealtorFirm>(realtorFirmPostDTO));
    // Save entity to db
    await _realtorFirmRepository.SaveChangesAsync();
    // Return success status code 201 with a reference to the newly created object's URL
    return CreatedAtAction(nameof(GetByIdAsync), new { id = realtorFirm.Id }, realtorFirm);
}

When I post in Swagger or Postman I get a response with a Location header containing a correct URL. All is fine.

But when I make a call from the Blazor client, the Location header returns null. Here's the call:

    HttpResponseMessage response = await httpClient.PostAsJsonAsync("https://localhost:7190/api/RealtorFirm", RealtorFirm);

    if(response.IsSuccessStatusCode)
    {
        // TODO: Get Location in Http-response and extract id

        // TODO: Redirect to to details page
    }

Additional info: the response contains a 201-Created status code and the entity is written to the database, even from the client. My problem is with finding out the Location and rerouting to the details page.

I have tried changing AllowAutoRedirect to false, but it didn't help. But I'm not sure I did it the right way (code from Program.cs):

HttpClientHandler handler = new HttpClientHandler()
{
    AllowAutoRedirect = false
};

builder.Services.AddScoped(sp => new HttpClient(handler)
{
    BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)
});

Am I misusing HttpResponseMessage? Or misunderstanding the use of CreatedAtAction()?

0