2

Env: C# Core 3.1 WebApi Project.

In my controller I'm trying to get the current URL but am getting a null value. I've tried a number of things using the Url class:

var x = Url.Link("https://localhost:44397/api/Account/Accounts/", new { a = 1, b = 2 });
var y = Url.RouteUrl("www.xyz.com", new { a = 3, b = 4 });
var url = Url.Link("GetAuthors", authorsResourceParameters);
var r = Url.RouteUrl("This route");
var yd = Url.Action("myAction", "myController", authorsResourceParameters, "https");

The Url class is from Microsoft.AspNetCore.Mvc.Routing.EndpointRoutingUrlHelper. Is this the correct namespace?

What am I missing?

3
  • why did you want to get the current URL? Commented Feb 18, 2020 at 19:31
  • Cause I want it. Commented Feb 18, 2020 at 19:52
  • well if we know the problem you're trying to solve, then maybe we can propose a better solution. Anyway, good luck with your solution. Commented Feb 19, 2020 at 6:10

1 Answer 1

1

You can use the below code:

var request = HttpContext.Request;

var uri = string.Concat(request.Scheme,"://",
                        request.Host.ToUriComponent(),
                        request.PathBase.ToUriComponent(),
                        request.Path.ToUriComponent(),
                        request.QueryString.ToUriComponent());

good luck.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.