Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the Web Root Path and the Content Root Path in ASP.NET Core?

Tags:

asp.net-core

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.

like image 310
Colin Avatar asked Dec 17 '22 21:12

Colin


2 Answers

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

like image 94
rBalzer Avatar answered May 31 '23 16:05

rBalzer


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.

like image 41
Colin Avatar answered May 31 '23 17:05

Colin