I'm trying to retrieve the current request url with routes values, in order to have a return url with all needed values when reaching my controllers.
I tried HttpContext.Request.Path and HttpContext.Request.GetDisplayUrl() but it returns something like :
/Home/Products
What I actually need is to retrive the routes values to have :
/Home/Products?id=1
Is there a way to achieve that?
Thanks !
You can do this
HttpContext.Request.Path + HttpContext.Request.QueryString
Or for convenience you can create an extension method like this
public static string GetCurrentUrl(this HttpRequest httpRequest)
{
return httpRequest.Path + httpRequest.QueryString;
}
Then get current URL
var url = HttpContext.Request.GetCurrentUrl();
This link maybe helpful for you.
does anyone know how to pass a URL as a query string parameter and then get the URl in HttpGet method as a parameter ?
Thanks so much for all the answers. Finally I got it sorted. Please refer to my fix below:
[Route("api/[controller]")]
public class UrlController : Controller
{
[HttpGet("{*longUrl}")]
public string ShortUrl(string longUrl)
{
var test = longUrl + Request.QueryString;
return JsonConvert.SerializeObject(GetUrlToken(test));
}
just like this?
current url with UrlEncode
[HttpGet]
public ActionResult Index(string url = null)
{
ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";
return View();
}
HttpUtility.UrlEncode should do the job for you
404 might be because the application is not in running mode
host you application and try it in local it should be working as needed
i was trying as http://localhost:11331/Home/?id=http%3A%2F%2Flocalhost%3A11331%2F
and everything is working fine even the redirection to the launch screen
or else post the complete URL you are getting so that i can help you
I asked a question to get URL as action input here. Now I have a new problem. The passed URL to action changes from http://example.com to http:/example.com.
I want to know why and how can I resolve the problem.
P.S: I added this code to resolve but I think there may be another problems in future! the code is:
if ((url.Contains(":/")) && !(url.Contains("://")))
{
url = url.Replace(":/", "://");
}
The browser (or server) is replacing a double slash (illegal) with a single one.
Try it,
http://stackoverflow.com/questions/11853025//input-url-like-http-site-com-changes-to-http-site-com-in-action-input
(in Chrome) goes to:
http://stackoverflow.com/questions/11853025/input-url-like-http-site-com-changes-to-http-site-com-in-action-input
If I were you, I would remove the http:// from your path and add it later.
http://localhost:1619/Utility/PR/example.com/
Then, url = "http://" + url;
If you might get secure urls, add that to the route /http/example.com or /https/example.com
use regex:
string src = #"http://example.com";
string result = Regex.Replace(src, #"(?<=https?:/)/", "");
if you need to revert:
string src = #"http:/example.com";
string result = Regex.Replace(src, #"(?<=https?:)/(?=[^/])", #"//");
Is there a better/more accurate/stricter method/way to find out if a URL is properly formatted?
Using:
bool IsGoodUrl = Uri.IsWellFormedUriString(url, UriKind.Absolute);
Doesn't catch everything. If I type htttp://www.google.com and run that filter, it passes. Then I get a NotSupportedExceptionlater when calling WebRequest.Create.
This bad url will also make it past the following code (which is the only other filter I could find):
Uri nUrl = null;
if (Uri.TryCreate(url, UriKind.Absolute, out nUrl))
{
url = nUrl.ToString();
}
The reason Uri.IsWellFormedUriString("htttp://www.google.com", UriKind.Absolute) returns true is because it is in a form that could be a valid Uri. URI and URL are not the same.
See: What's the difference between a URI and a URL?
In your case, I would check that new Uri("htttp://www.google.com").Scheme was equal to http or https.
Technically, htttp://www.google.com is a properly formatted URL, according the URL specification. The NotSupportedException was thrown because htttp isn't a registered scheme. If it was a poorly-formatted URL, you would have gotten a UriFormatException. If you just care about HTTP(S) URLs, then just check the scheme as well.
#Greg's solution is correct. However you can steel using URI and validate all protocols (scheme) that you want as valid.
public static bool Url(string p_strValue)
{
if (Uri.IsWellFormedUriString(p_strValue, UriKind.RelativeOrAbsolute))
{
Uri l_strUri = new Uri(p_strValue);
return (l_strUri.Scheme == Uri.UriSchemeHttp || l_strUri.Scheme == Uri.UriSchemeHttps);
}
else
{
return false;
}
}
This Code works fine for me to check a Textbox have valid URL format
if((!string.IsNullOrEmpty(TXBProductionURL.Text)) && (Uri.IsWellFormedUriString(TXBProductionURL.Text, UriKind.Absolute)))
{
// assign as valid URL
isValidProductionURL = true;
}
I am really surprised that there is no native .NET method to get an absolute url from a relative url. I know this has been discussed many times, but never have come across a satisfactory method that handles this well. Can you help fine tune the method below?
I think all I need left is to auto choose the protocol instead of hard coding it (http/https). Anything else I am missing (caveats, performance, etc)?
public static string GetAbsoluteUrl(string url)
{
//VALIDATE INPUT FOR ALREADY ABSOLUTE URL
if (url.StartsWith("http://", StringComparison.OrdinalIgnoreCase)
|| url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{
return url;
}
//GET PAGE REFERENCE FOR CONTEXT PROCESSING
Page page = HttpContext.Current.Handler as Page;
//RESOLVE PATH FOR APPLICATION BEFORE PROCESSING
if (url.StartsWith("~/"))
{
url = page.ResolveUrl(url);
}
//BUILD AND RETURN ABSOLUTE URL
return "http://" + page.Request.ServerVariables["SERVER_NAME"] + "/"
+ url.TrimStart('/');
}
This has always been my approach to this little nuisance. Note the use of VirtualPathUtility.ToAbsolute(relativeUrl) allows the method to be declared as an extension in a static class.
/// <summary>
/// Converts the provided app-relative path into an absolute Url containing the
/// full host name
/// </summary>
/// <param name="relativeUrl">App-Relative path</param>
/// <returns>Provided relativeUrl parameter as fully qualified Url</returns>
/// <example>~/path/to/foo to http://www.web.com/path/to/foo</example>
public static string ToAbsoluteUrl(this string relativeUrl) {
if (string.IsNullOrEmpty(relativeUrl))
return relativeUrl;
if (HttpContext.Current == null)
return relativeUrl;
if (relativeUrl.StartsWith("/"))
relativeUrl = relativeUrl.Insert(0, "~");
if (!relativeUrl.StartsWith("~/"))
relativeUrl = relativeUrl.Insert(0, "~/");
var url = HttpContext.Current.Request.Url;
var port = url.Port != 80 ? (":" + url.Port) : String.Empty;
return String.Format("{0}://{1}{2}{3}",
url.Scheme, url.Host, port, VirtualPathUtility.ToAbsolute(relativeUrl));
}
new System.Uri(Page.Request.Url, "/myRelativeUrl.aspx").AbsoluteUri
This one works for me...
new System.Uri(Page.Request.Url, ResolveClientUrl("~/mypage.aspx")).AbsoluteUri
With ASP.NET, you need to consider the reference point for a "relative URL" - is it relative to the page request, a user control, or if it is "relative" simply by virtue of using "~/"?
The Uri class contains a simple way to convert a relative URL to an absolute URL (given an absolute URL as the reference point for the relative URL):
var uri = new Uri(absoluteUrl, relativeUrl);
If relativeUrl is in fact an abolute URL, then the absoluteUrl is ignored.
The only question then remains what the reference point is, and whether "~/" URLs are allowed (the Uri constructor does not translate these).
Here is my own version that handles many validations and relative pathing from user's current location option. Feel free to refactor from here :)
/// <summary>
/// Converts the provided app-relative path into an absolute Url containing
/// the full host name
/// </summary>
/// <param name="relativeUrl">App-Relative path</param>
/// <returns>Provided relativeUrl parameter as fully qualified Url</returns>
/// <example>~/path/to/foo to http://www.web.com/path/to/foo</example>
public static string GetAbsoluteUrl(string relativeUrl)
{
//VALIDATE INPUT
if (String.IsNullOrEmpty(relativeUrl))
return String.Empty;
//VALIDATE INPUT FOR ALREADY ABSOLUTE URL
if (relativeUrl.StartsWith("http://", StringComparison.OrdinalIgnoreCase)
|| relativeUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
return relativeUrl;
//VALIDATE CONTEXT
if (HttpContext.Current == null)
return relativeUrl;
//GET CONTEXT OF CURRENT USER
HttpContext context = HttpContext.Current;
//FIX ROOT PATH TO APP ROOT PATH
if (relativeUrl.StartsWith("/"))
relativeUrl = relativeUrl.Insert(0, "~");
//GET RELATIVE PATH
Page page = context.Handler as Page;
if (page != null)
{
//USE PAGE IN CASE RELATIVE TO USER'S CURRENT LOCATION IS NEEDED
relativeUrl = page.ResolveUrl(relativeUrl);
}
else //OTHERWISE ASSUME WE WANT ROOT PATH
{
//PREPARE TO USE IN VIRTUAL PATH UTILITY
if (!relativeUrl.StartsWith("~/"))
relativeUrl = relativeUrl.Insert(0, "~/");
relativeUrl = VirtualPathUtility.ToAbsolute(relativeUrl);
}
var url = context.Request.Url;
var port = url.Port != 80 ? (":" + url.Port) : String.Empty;
//BUILD AND RETURN ABSOLUTE URL
return String.Format("{0}://{1}{2}{3}",
url.Scheme, url.Host, port, relativeUrl);
}
If you're in the context of an MVC Controller or View you can use the UrlHelper which should be accessible via just Url
Url.Content("~/content/images/myimage.jpg")
Which will be fully expanded to /virtual_directoryname/content/images/myimage.jpg
This can be used in a controller or .cshtml file
Yes it is a little odd that it's called Content but it's meant to be used to get an absolute path to a resource so it makes sense
Still nothing good enough using native stuff. Here is what I ended up with:
public static string GetAbsoluteUrl(string url)
{
//VALIDATE INPUT
if (String.IsNullOrEmpty(url))
{
return String.Empty;
}
//VALIDATE INPUT FOR ALREADY ABSOLUTE URL
if (url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{
return url;
}
//GET CONTEXT OF CURRENT USER
HttpContext context = HttpContext.Current;
//RESOLVE PATH FOR APPLICATION BEFORE PROCESSING
if (url.StartsWith("~/"))
{
url = (context.Handler as Page).ResolveUrl(url);
}
//BUILD AND RETURN ABSOLUTE URL
string port = (context.Request.Url.Port != 80 && context.Request.Url.Port != 443) ? ":" + context.Request.Url.Port : String.Empty;
return context.Request.Url.Scheme + Uri.SchemeDelimiter + context.Request.Url.Host + port + "/" + url.TrimStart('/');
}
When you want to generate URL from your Business Logic layer, you do not have the flexibility of using ASP.NET Web Form's Page class/ Control's ResolveUrl(..) etc. Moreover, you may need to generate URL from ASP.NET MVC controller too where you not only miss the Web Form's ResolveUrl(..) method, but also you cannot get the Url.Action(..) even though Url.Action takes only Controller name and Action name, not the relative url.
I tried using
var uri = new Uri(absoluteUrl, relativeUrl)
approach, but there is a problem too. If the web application is hosted in IIS virtual directory, where the url of the app is like this : http://localhost/MyWebApplication1/, and the relative url is "/myPage" then the relative url is resolved as "http://localhost/MyPage" which is another problem.
Therefore, in order to overcome such problems, I have written a UrlUtils class which can work from a class library. So, it wont depend on Page class but it depends on ASP.NET MVC. So, if you dont mind adding reference to MVC dll to your class library project then my class will work smoothly. I have tested in IIS virtual directory scenario where the web application url is like this : http://localhost/MyWebApplication/MyPage. I realized that, sometimes we need to make sure that the Absolute url is SSL url or non SSL url. So, I wrote my class library supporting this option. I have restricted this class library so that the relative url can be absolute url or a relative url that starts with '~/'.
Using this library, I can call
string absoluteUrl = UrlUtils.MapUrl("~/Contact");
Returns : http://localhost/Contact
when the page url is : http://localhost/Home/About
Returns : http://localhost/MyWebApplication/Contact
when the page url is : http://localhost/MyWebApplication/Home/About
string absoluteUrl = UrlUtils.MapUrl("~/Contact", UrlUtils.UrlMapOptions.AlwaysSSL);
Returns : **https**://localhost/MyWebApplication/Contact
when the page url is : http://localhost/MyWebApplication/Home/About
Here is my class Library :
public class UrlUtils
{
public enum UrlMapOptions
{
AlwaysNonSSL,
AlwaysSSL,
BasedOnCurrentScheme
}
public static string MapUrl(string relativeUrl, UrlMapOptions option = UrlMapOptions.BasedOnCurrentScheme)
{
if (relativeUrl.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ||
relativeUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
return relativeUrl;
if (!relativeUrl.StartsWith("~/"))
throw new Exception("The relative url must start with ~/");
UrlHelper theHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);
string theAbsoluteUrl = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) +
theHelper.Content(relativeUrl);
switch (option)
{
case UrlMapOptions.AlwaysNonSSL:
{
return theAbsoluteUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
? string.Format("http://{0}", theAbsoluteUrl.Remove(0, 8))
: theAbsoluteUrl;
}
case UrlMapOptions.AlwaysSSL:
{
return theAbsoluteUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase)
? theAbsoluteUrl
: string.Format("https://{0}", theAbsoluteUrl.Remove(0, 7));
}
}
return theAbsoluteUrl;
}
}
The final version taking care of all previous complaints (ports, logical url, relative url, existing absolute url...etc.) considering the current handler is the page:
public static string ConvertToAbsoluteUrl(string url)
{
if (!IsAbsoluteUrl(url))
{
if (HttpContext.Current != null && HttpContext.Current.Request != null && HttpContext.Current.Handler is System.Web.UI.Page)
{
var originalUrl = HttpContext.Current.Request.Url;
return string.Format("{0}://{1}{2}{3}", originalUrl.Scheme, originalUrl.Host, !originalUrl.IsDefaultPort ? (":" + originalUrl.Port) : string.Empty, ((System.Web.UI.Page)HttpContext.Current.Handler).ResolveUrl(url));
}
throw new Exception("Invalid context!");
}
else
return url;
}
private static bool IsAbsoluteUrl(string url)
{
Uri result;
return Uri.TryCreate(url, UriKind.Absolute, out result);
}
check the following code to retrieve absolute Url :
Page.Request.Url.AbsoluteUri
I hope to be useful.
This works fine too:
HttpContext.Current.Server.MapPath(relativePath)
Where relative path is something like "~/foo/file.jpg"