I am trying to add a root path as a parameter in a View, so I can pass it as a parameter to a PayPal button.
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" target="_top">
... snip ...
<input type="hidden" name="return" value="@Model.UrlRoot/Manage/[email protected]">
... snip ...
</form>
I was sifting through the answers at How can I get my webapp's base URL in ASP.NET MVC? (20 answers) and ASP.NET MVC 6 application's virtual application root path
Since ASP.NET Core is quite different, the Request class no longer contains a .Url property, so most of those answers don't work.
You can inject the IHostingEnvironment into the Controller like this:
public class HomeController : Controller
{
protected readonly IHostingEnvironment _hostingEnvironment;
public HomeController(IHostingEnvironment hostingEnvironment)
{
}
}
In your _ViewImports.cshtml add:
@using Microsoft.AspNetCore.Hosting
@inject IHostingEnvironment HostingEnvironment
Now you can use can use HostingEnvironment
and all its properties in your form.
For example HostingEnvironment.WebRootPath
or HostingEnvironment.ContentRootPath
I came across Marius Schulz's post. (If you are Marius, please add your answer, contact me and I'll remove mine.)
https://blog.mariusschulz.com/2016/05/22/getting-the-web-root-path-and-the-content-root-path-in-asp-net-core
For some reason my Controllers don't have the IHostingEnvironment injected in the constructor, but they do have the Request object.
In my Controller, I've declared
var urlRoot = $"{Request.Scheme}://{Request.Host}{Url.Content("~")}";
and passed it to MyViewModel
var model = new MyViewModel { UrlRoot = urlRoot };
return View(model);
This takes into account http vs. https, port numbers, and hopefully, the site root if the web site is not rooted at /. Since my site is at / I cannot confirm that Url.Content("~") gets the site root.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With