How to get base url of the site in MVC [duplicate]

2019-04-28 17:51发布

问题:

This question already has an answer here:

  • How can I get my webapp's base URL in ASP.NET MVC? 20 answers

I want to send an email to the user where he can click on link to transfer to my site. I don't want to hard code the url in my Email Templates. I want this dynamic in a sense that whatever the environment it will send the related url. Like If I am on the development environment it send something like http://localhost:port or in production send the actual website url. http://www.domain.com

I just need to know how can I save it in DynamicViewBag in MVC Action. Any suggestion plz?

回答1:

You can do this:

var dynamicViewBag = new DynamicViewBag();
dynamicViewBag.AddValue("BaseUrl", Request.Url.GetLeftPart(UriPartial.Authority));


回答2:

You can use the properties of the Request object, for example

var request = HttpContext.Current.Request
var address = string.Format("{0}://{1}", request.Url.Scheme, request.Url.Authority);