How can I quickly determine what the root URL is for my ASP.NET MVC application? I.e., if IIS is set to serve my application at http://example.com/foo/bar, then I'd like to be able to get that URL in a reliable way that doesn't involve getting the current URL from the request and chopping it up in some fragile way that breaks if I re-route my action.
The reason that I need the base URL is that this web application calls another one that needs the root to the caller web application for callback purposes.
Assuming you have a Request object available, you can use:
string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"));
If it's not available, you can get to it via the context:
var request = HttpContext.Current.Request
So none of the ones listed here worked for me, but using a few of the answers, I got something working:
public string GetBaseUrl()
{
var request = HttpContext.Current.Request;
var appUrl = HttpRuntime.AppDomainAppVirtualPath;
if (appUrl != "/")
appUrl = "/" + appUrl;
var baseUrl = string.Format("{0}://{1}{2}", request.Url.Scheme, request.Url.Authority, appUrl);
return baseUrl;
}
Update for ASP.NET Core / MVC 6:
ASP.NET Core makes this process a bit more painful, especially if you are deep in your code. You have 2 options to get at the HttpContext
1) Pass it in from your controller:
var model = new MyClass(HttpContext);
then in model:
private HttpContext currentContext;
public MyClass(HttpContext currentContext)
{
this.currentContext = currentContext;
}
2) Perhaps the cleaner way is to inject it into your class, which starts with registering the types in your Startup:
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddMvc();
services.AddTransient<MyClass, MyClass>();
services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
then have it injected for you like this:
private HttpContext currentContext;
public MyClass(IHttpContextAccessor httpContextAccessor)
{
currentContext = httpContextAccessor.HttpContext;
}
in either case, here is the updated for .NET Core GetBaseUrl():
public string GetBaseUrl()
{
var request = currentContext.Request;
var host = request.Host.ToUriComponent();
var pathBase = request.PathBase.ToUriComponent();
return $"{request.Scheme}://{host}{pathBase}";
}
In Code:
Url.Content("~/");
MVC3 Razor Syntax:
#Url.Content("~/")
Maybe it is extension or modification of the answers posted here but I use simply the following line and it works:
Request.Url.GetLeftPart(UriPartial.Authority) + Url.Content("~")
When my path is: http://host/iis_foldername/controller/action
then I receive : http://host/iis_foldername/
The following snippet works nicely for me in MVC4, and doesn't need an HttpContext available:
System.Web.HttpRuntime.AppDomainAppVirtualPath
The trick with relying upon IIS is that IIS bindings can be different from your public URLs (WCF I'm looking at you), especially with multi-homed production machines. I tend to vector toward using configuration to explicitly define the "base" url for external purposes as that tends to be a bit more successful than extracting it from the Request object.
For an absolute base URL use this. Works with both HTTP and HTTPS.
new Uri(Request.Url, Url.Content("~"))
This is a conversion of an asp.net property to MVC . It's a pretty much all singing all dancing get root url method.
Declare a helper class:
namespace MyTestProject.Helpers
{
using System.Web;
public static class PathHelper
{
public static string FullyQualifiedApplicationPath(HttpRequestBase httpRequestBase)
{
string appPath = string.Empty;
if (httpRequestBase != null)
{
//Formatting the fully qualified website url/name
appPath = string.Format("{0}://{1}{2}{3}",
httpRequestBase.Url.Scheme,
httpRequestBase.Url.Host,
httpRequestBase.Url.Port == 80 ? string.Empty : ":" + httpRequestBase.Url.Port,
httpRequestBase.ApplicationPath);
}
if (!appPath.EndsWith("/"))
{
appPath += "/";
}
return appPath;
}
}
}
Usage:
To use from a controller:
PathHelper.FullyQualifiedApplicationPath(ControllerContext.RequestContext.HttpContext.Request)
To use in a view:
#using MyTestProject.Helpers
PathHelper.FullyQualifiedApplicationPath(Request)
In MVC _Layout.cshtml:
<base href="#Request.GetBaseUrl()" />
Thats what we use!
public static class ExtensionMethods
{
public static string GetBaseUrl(this HttpRequestBase request)
{
if (request.Url == (Uri) null)
return string.Empty;
else
return request.Url.Scheme + "://" + request.Url.Authority + VirtualPathUtility.ToAbsolute("~/");
}
}
This works fine for me (also with a load balancer):
#{
var urlHelper = new UrlHelper(Html.ViewContext.RequestContext);
var baseurl = urlHelper.Content(“~”);
}
<script>
var base_url = "#baseurl";
</script>
Especially if you are using non-standard port numbers, using Request.Url.Authority appears like a good lead at first, but fails in a LB environment.
You could have a static method that looks at HttpContext.Current and decides which URL to use (development or live server) depending on the host ID. HttpContext might even offer some easier way to do it, but this is the first option I found and it works fine.
You can use the following script in view:
<script type="text/javascript">
var BASE_URL = '<%= ResolveUrl("~/") %>';
</script>
For ASP.NET MVC 4 it is a bit different:
string url = HttpContext.Request.Url.AbsoluteUri;
This is working in ASP .NET MVC 4
In any controller action you can write:
1stline gets the whole url+Query String.
2nd line remove local path & query ,last '/' symbol.
3rd line add '/' symbol at last position.
Uri url = System.Web.HttpContext.Current.Request.Url;
string UrlLink = url.OriginalString.Replace(url.PathAndQuery,"");
UrlLink = String.Concat(UrlLink,"/" );
in simple html and ASP.NET or ASP.NET MVC if you are using tag:
About us
For url with aplication alias like http://example.com/appAlias/... You can try this:
var req = HttpContext.Current.Request;
string baseUrl = string.Format("{0}://{1}/{2}", req.Url.Scheme, req.Url.Authority, req.ApplicationPath);
On the webpage itself:
<input type="hidden" id="basePath" value="#string.Format("{0}://{1}{2}",
HttpContext.Current.Request.Url.Scheme,
HttpContext.Current.Request.Url.Authority,
Url.Content("~"))" />
In the javascript:
function getReportFormGeneratorPath() {
var formPath = $('#reportForm').attr('action');
var newPath = $("#basePath").val() + formPath;
return newPath;
}
This works for my MVC project, hope it helps
This was my solution (using .net core 3.1, in an api controller):
string baseUrl = $"{Request.Scheme}://{Request.Headers.Where(h => h.Key == "Host").First().Value}";
For MVC 4:
String.Format("{0}://{1}{2}", Url.Request.RequestUri.Scheme, Url.Request.RequestUri.Authority, ControllerContext.Configuration.VirtualPathRoot);
I put this in the head of my _Layout.cshtml
<base href="~/" />
Maybe it is a better solution.
#{
var baseUrl = #Request.Host("/");
}
using
Base URL
#{
var baseurl = Request.Url.Scheme + "://" + Request.Url.Host + ":" + Request.Url.Port + Url.Content("~");
}
#baseurl
--output
http://localhost:49626/TEST/
In .net core 3.1 I used this approach:
$"{Request.Scheme}://{Request.Host}{Url.Content("~/")}"
The following worked solidly for me
var request = HttpContext.Request;
var appUrl = System.Web.HttpRuntime.AppDomainAppVirtualPath;
if (appUrl != "/")
appUrl = "/" + appUrl + "/";
var newUrl = string.Format("{0}://{1}{2}{3}/{4}", request.Url.Scheme, request.UrlReferrer.Host, appUrl, "Controller", "Action");
Also you can use this. For the razor pages, it is better to use it than the others.
https://ml-software.ch/posts/getting-the-base-url-for-an-asp-net-core-mvc-web-application-in-your-static-javascript-files
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<base href='#Url.AbsoluteContent("~/")'>
<title>#ViewBag.Title - ASP.NET Core Web Application</title>
<!-- ... -->
</head>
<body>
add this function in static class in project like utility class:
utility.cs content:
public static class Utility
{
public static string GetBaseUrl()
{
var request = HttpContext.Current.Request;
var urlHelper = new UrlHelper(request.RequestContext);
var baseUrl = $"{request.Url.Scheme}://{request.Url.Authority}{urlHelper.Content("~")}";
return baseUrl;
}
}
use this code any where and enjoy it:
var baseUrl = Utility.GetBaseUrl();
Simply in one line get BaseUrl
string baseUrl = new Uri(Request.Url, Url.Content("~")).AbsoluteUri;
//output example: https://stackoverflow.com
i m using jsoup Application and trying to get url of web pages. i got urls of web page. i m trying to get only image urls via url parsing
but when sending request to url i got this error
" The constructor URL(Elements) is undefined "
my question is how can i pass urls that i got from jsoup library
here is my code
' public static void main(String[] args) throws IOException {
Validate.isTrue(args.length == 1, "usage: supply url to fetch");
String url = args[0];
print("Fetching %s...", url);
Document doc = Jsoup.connect(url).get();
Elements links = doc.select("a[href]");
Elements media = doc.select("[src]");
Elements imports = doc.select("link[href]");
'
and using
'Elements imagepath = doc.select("[src]");'
and passing this Lement into url parsing function
URL url = new URL(imagepath);
can anyone help me to figure it out how to get url parsing function works
thanks in advance
The reason you get that exception is because you pass Elements to the URL constructor - the Elements is just the specialization of List<Element>. This means you probably have more than one image assigned to imagepath variable. If you would like to construct the URL objects from the scraped images, consider this code sample:
Elements images = document.select("img");
for (Element element : images) {
System.out.println(element.attr("abs:src"));
}
This should help you making progress with your application. I would love to answer any further question you might have.
In my controller I return a file,it is OK.But in the view,I use location.href=url,sometimes if the url parameter is too long,I can not download the file.Is the max length of url is 1024B?How to solve the solve the question if the question if the url parameter is too long?Must I change the view code,or change the iis config?
MVC View function
//studentName may be very long
function GetFile(){
var searchCondiction = {
studentName: $("#studentName").val(),
startDate: $("#UploadYear").val(),
};
location.href = "#Url.Action("GetFile", "Student")?" + $.param(searchCondiction );
}
MVC Controller function
public ActionResult GetFile(string studentName,DateTime startDate)
{
//Product file according to studentName and startDate
...
//Return file
Return File(Server.MapPath("~/App_Data/UserA/a.png"),"imge/png");
}
You need to make the url shorter. one way would be to store the parameters serverside, and just return a key.
How can I implement a "slug" (I believe is the right term) in the URL? Say the URL is
www.example.com/module/controller/action1/123
or
www.example.com/module/controller/action1/123/abc
and I want my action1 controller action method hit, and I want to be able to access the value 123, or even 123 and abc, how could I do that?
public function action1Action()
{
$request = $this->getRequest();
$data = $request->getParams();
var_dump($data);
}
Magento uses next scheme to access values in url (aside from normal GET request):
www.example.com/module/controller/action1/[key]/[value]/[key2]/[value2]
In the controller method action1Action you'll use
$value1 = $this->getRequest()->getParam('[key1]'); // [value1]
$value2 = $this->getRequest()->getParam('[key2]'); // [value2]
Question:
I am creating a wiki software, basically a clone of wikipedia/mediawiki, but in ASP.NET MVC (the MVC is the point, so don't recommend me ScrewTurn).
Now I have a question:
I use this route mapping, to route a URL like:
http://en.wikipedia.org/wiki/ASP.NET
routes.MapRoute(
"Wiki", // Routenname
//"{controller}/{action}/{id}", // URL mit Parametern
"wiki/{id}", // URL mit Parametern
new { controller = "Wiki", action = "dbLookup", id = UrlParameter.Optional } // Parameterstandardwerte
);
Now it just occured to me, that there might be titles like 'AS/400':
http://en.wikipedia.org/wiki/AS/400
Incidentially, there is also this one (title 'Slash'):
http://en.wikipedia.org/wiki//
And this one:
http://en.wikipedia.org/wiki//dev/null
Overall, Wikipedia seems to have a list of interesting titles like this:
http://en.wikipedia.org/wiki/Wikipedia:Articles_with_slashes_in_title
How do I make routes like this route correctly ?
Edit:
Something like:
If the URL starts with /Wiki/, and if it doesn't start with /wiki/Edit/
(but not /Wiki/Edit)
then pass all the rest of the URL as Id.
Edit:
Hmm, just another problem:
How can I route this one:
http://en.wikipedia.org/wiki/C&A
Wikipedia can...
Edit:
According to wikipedia, due to clashes with wikitext syntax, only the following characters can never be used in page titles (nor are they supported by DISPLAYTITLE):
# < > [ ] | { }
http://en.wikipedia.org/wiki/Wikipedia:Naming_conventions_(technical_restrictions)#Forbidden_characters
Edit:
To allow * and &, put
<httpRuntime requestPathInvalidCharacters="" />
into section <system.web> in file web.config
(Found here: http://www.christophercrooker.com/use-any-characters-you-want-in-your-urls-with-aspnet-4-and-iis)
You could use a catchall route to capture everything that follows the wiki part of the url into the id token:
routes.MapRoute(
"Wiki",
"wiki/{*id}",
new { controller = "Wiki", action = "DbLookup", id = UrlParameter.Optional }
);
Now if you have the following request: /wiki/AS/400 it will map to the following action on the Wiki controller:
public ActionResult DbLookup(string id)
{
// id will equal AS/400 here
...
}
As far as /wiki// is concerned I believe you will get a 400 Bad Request error from the web server before this request ever reaches the ASP.NET pipeline. You may checkout the following blog post.
in Attribute Routing in mvc i had the same problem having / in string abc/cde in HttpGet
[Route("verifytoken/{*token}")]
[AllowAnonymous]
[HttpGet]
public ActionResult VerifyToken(string token)
{
//logic here
}
so you have to place * because after this it will be considered as parameter
#Darin: Well, that much is obvious, the question is: Why ? controller
+ action + id are given, it's like it's passing all these to routing again... – Quandary Jun 13 '11 at 17:38
Quandry - maybe you have already figured this out since your question is over a year old, but when you call RedirectToAction, you are actually sending an HTTP 302 response to the browser, which causes the browser to make a GET request to the specified action. Hence, the infinite loop you are seeing.
See: Controller.RedirectToAction Method
Still as an option write in the file Global.asax:
var uri = Context.Request.Url.ToString();
if (UriHasRedundantSlashes(uri))
{
var correctUri = RemoveRedundantSlashes(uri);
Response.RedirectPermanent(correctUri);
}
}
private string RemoveRedundantSlashes(string uri)
{
const string http = "http://";
const string https = "https://";
string prefix = string.Empty;
if (uri.Contains(http))
{
uri = uri.Replace(http, string.Empty);
prefix = http;
}
else if (uri.Contains(https))
{
uri = uri.Replace(https, string.Empty);
prefix = https;
}
while (uri.Contains("//"))
{
uri = uri.Replace("//", "/");
}
if (!string.IsNullOrEmpty(prefix))
{
return prefix + uri;
}
return uri;
}
private bool UriHasRedundantSlashes(string uri)
{
const string http = "http://";
const string https = "https://";
if (uri.Contains(http))
{
uri = uri.Replace(http, string.Empty);
}
else if (uri.Contains(https))
{
uri = uri.Replace(https, string.Empty);
}
return uri.Contains("//");
}