me.at.coding
me.at.coding

Reputation: 17858

Get absolute URL inside Web API Controller?

In my Controller I can't use CreatedAtAction for reasons out of the scope of this question. I therefore need to do the following, however I don't know how to get the absolute URL of the Web API to correctly set the Location header?

public async Task<ActionResult<string>> PostItem(ItemPostRequest itemPostRequest)
{
    // call repository etc.

    string baseUrl= // <------- how to get this?
    Response.Headers.Add("Location", baseUrl + insertId);

    return Content(savedItem, "application/json", System.Text.Encoding.UTF8);
}

I am on .NET 5.0, in case this matters.

Upvotes: 0

Views: 3282

Answers (1)

Prasad Ramireddy
Prasad Ramireddy

Reputation: 297

string baseUrl = $"{Request.Scheme}://{Request.Host.Value}/{Request.Path}";

Upvotes: 4

Related Questions