4

I want to ask something. I build a simple email sender using asp.net core 2.0 and I want to send an email with a link to redirect the receiver into my web page like email authentication but I don't know how to make the callback URL.

I use :

<a href='https://"+Request.Scheme+"/Users/Userrole'>Click Here</a>

but the link in email was http:/Users/Userrole

Please tell me how to get the dynamic URL to my page, because using Localhost:443xx/User/Userrole is not elegant and does not work when I run on my local computer

Edit, the very simple method to do this action is <a href='https://"+this.Request.Host+"/Users/Userrole'>Click Here</a>

Thanks to FrustatedDeveloper for this answer

Dewa Dwi
  • 105
  • 2
  • 9

1 Answers1

3

Asp.Net Core

In Asp.Net Core you can use the following to get the URL:

var url = $"{Context.Request.Scheme}://{Context.Request.Host}{Context.Request.Path}";
var link = $"<a href='{url}'>Click here</a>";

If you need to get the query string then you can use:

var queryString = Context.Host.QueryString;

Please check the following resource: HttpRequest.

If you include using Microsoft.AspNetCore.Http.Extensions then you can also use:

var url = httpContext.Request.GetEncodedUrl();

Or

var url = httpContext.Request.GetDisplayUrl();

Original Answer (Asp.Net/MVC framework)

To create a dynamic URL you can use the UrlHelper @Url.Action("ActionName", "ControllerName") along with Request.Url.Authority for the domain and Request.Url.Scheme for the scheme (using http or https).

var url = $"{Request.Url.Scheme}://{Request.Url.Authority}{@Url.Action("UserRole","Users")}";
var link = $"<a href='{url}'>Click here</a>";

Assuming your site has a domain www.example.com this would procude a URL like:

https://www.example.com/users/userrole

The above uses string interpolation to combine the string variables.

haldo
  • 14,512
  • 5
  • 46
  • 52
  • i'm sorry i was type like your code, but i have error 'HTTPRequest' doesn't contain a definition for 'Url', do i need import some library? – Dewa Dwi Sep 26 '19 at 00:52
  • @DewaDwi Hi, sorry, I didn't notice the .Net core tag. I've updated my answer :) – haldo Sep 26 '19 at 08:22
  • im trying to do the same thing in my asp.net core 3.0 app but its not working. im trying to generate a link to send thru email in my controller. – hello world Apr 05 '20 at 20:36
  • @helloworld have you tried using the [Url.Link](https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.routing.urlhelper.link?view=aspnetcore-2.1) method? – haldo Apr 05 '20 at 22:20