asp.netasp.net-coremail-sender

How To Make Dynamic Link On Email in ASP.NET Core


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


Solution

  • 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.