8

How to get current URL? I try that:

Program.cs

var location = new Uri($"{Request.Scheme}://{Request.Host}{Request.Path}{Request.QueryString}");

or

public string BuildAbsolute(PathString path, QueryString query = default(QueryString), FragmentString fragment = default(FragmentString))
    {
        var rq = HttpContent.Request;
        return Microsoft.AspNetCore.Http.Extensions.UriHelper.BuildAbsolute(rq.Scheme, rq.Host, rq.PathBase, path, query, fragment);
    }

Visual Studio does not find "Request"

The only thing I need is to take the current URL and Host / Path

2
  • 4
    Program.cs runs in order to start the kestrel web server, only after kestrel launches does it begin listen for web requests so there is no web request at the time when Program.cs main is executed. Feb 1, 2018 at 20:27
  • for what you need the url? when you need the url most likey you won't need it in program.cs there you can just set it.
    – Radu
    Apr 1, 2018 at 9:54

1 Answer 1

3

You can run your functions inside Startup.cs inside Configure using middleware. You can do

app.Use(async (context,next)=>{
     //Do what you want with context,which is HttpContext
     await next.Invoke();
});
2
  • This is useful to make basic context information like current URL available inside whole app without bloating it with HttpContextAccessor.
    – nielo
    Apr 24, 2018 at 7:52
  • How do you pass down context properties to your controller from the middle ware? Aug 26, 2020 at 17:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.