Warren  P Warren P - 1 year ago 312
ASP.NET (C#) Question

What is the ASP.NET Core MVC equivalent to Request.RequestURI?

I found a blog post that shows how to "shim" familiar things like HttpResponseMessage back into ASP.NET Core MVC, but I want to know what's the new native way to do the same thing as the following code in a REST Post method in a Controller:

// POST audit/values
public System.Net.Http.HttpResponseMessage Post([FromBody]string value)
var NewEntity = _repository.InsertFromString(value);

var msg = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Created);
msg.Headers.Location = new Uri(Request.RequestUri + NewEntity.ID.ToString());
return msg;


In an ASP.NET Core MVC project, I can't seem to get Request.RequestUri.

I tried inspecting Request, and I was able to make a function like this:

private string UriStr(HttpRequest Request)
return Request.Scheme + "://" + Request.Host + Request.Path; // Request.Path has leading /

So I could write
instead. But I'm not sure that's right. I feel like I'm hacking my way around, and not using this correctly.

A related question for earlier non-Core ASP.NET MVC versions asks how to get the base url of the site.

Answer Source

A cleaner way would be to use a UriBuilder:

    private static Uri GetUri(HttpRequest request)
        var builder = new UriBuilder();
        builder.Scheme = request.Scheme;
        builder.Host = request.Host.Value;
        builder.Path = request.Path;
        builder.Query = request.QueryString.ToUriComponent();
        return builder.Uri;

(not tested, the code might require a few adjustments)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download