Absolute URL from base + relative URL in C# - c#

I have a base URL :
http://my.server.com/folder/directory/sample
And a relative one :
../../other/path
How to get the absolute URL from this ? It's pretty straighforward using string manipulation, but I would like to do this in a secure way, using the Uri class or something similar.
It's for a standard a C# app, not an ASP.NET one.

var baseUri = new Uri("http://my.server.com/folder/directory/sample");
var absoluteUri = new Uri(baseUri,"../../other/path");
OR
Uri uri;
if ( Uri.TryCreate("http://base/","../relative", out uri) ) doSomething(uri);

Some might be looking for Javascript solution that would allow conversion of urls 'on the fly' when debugging
var absoluteUrl = function(href) {
var link = document.createElement("a");
link.href = href;
return link.href;
}
use like:
absoluteUrl("http://google.com")
http://google.com/
or
absoluteUrl("../../absolute")
http://stackoverflow.com/absolute

Related

How can I send URL parameter in ASP.NET Core Web API parameters

I wrote this code in a C# ASP.NET Core Web API project:
[HttpGet]
[Route("GetShortURL/{_url}/{tokenPass}")]
[ApiExplorerSettings(GroupName = "ShortURL")]
public ActionResult<ServiceResult<string>> GetShortURL(string _url, string tokenPass)
When I enter this parameter as _url, I get an error:
Error: Not Found
https://github.com/VahidN/DNTPersianUtils.Core
http://...//GetShortURL/https%3A%2F%2Fgithub.com%2FVahidN%2FDNTPersianUtils.Core/TokenPass
How can I call this API with the first Web URL parameter?
when i change the [Route("GetShortURL/{_url}/{tokenPass}")] to [Route("GetShortURL")] the problem was solved but i want to send query by / not by ?
for example, i want to call API like this :
1- http://..../GetShortURL/_UrlParam/_TokenPassParam
not like below :
2- http://..../GetShortURL?_url=_urlParam&tokenPass=_TokenPassParam
the second way works fine but I want first way to work correctly when i pass an URL like this
https%3A%2F%2Fgithub.com%2FVahidN%2FDNTPersianUtils.Core
can anyone help me?
First approach:
Pass the params you want as query string and then change the method like below:
[HttpGet("GetShortURL")]
[ApiExplorerSettings(GroupName = "ShortURL")]
public ActionResult<ServiceResult<string>> GetShortURL(string _url, string tokenPass)
Then For extracting the different parts of the url (protocol, domain name, path and query string), use the code below (path is an array separated by slash):
try
{
var decodedUrl = System.Web.HttpUtility.UrlDecode(_url);
Uri uri = new Uri(decodedUrl);
var scheme = uri.Scheme;
var host = uri.Host;
var absolutePathSeperatedBySlash = uri.AbsolutePath.Split('/').Skip(1).ToList();
var query = uri.Query;
// rest of the code ...
}
catch (Exception ex)
{
//...
}
Second approach:
If you want it to be sent as a url parameter, first you have to encode the value of _url with encodeURIComponent() in javascript, to make sure that some special characters like , / ? : # & = + $ # are changed.
Then:
[HttpGet("GetShortURL/{_url}/{tokenPass}")]
[ApiExplorerSettings(GroupName = "ShortURL")]
public ActionResult<ServiceResult<string>> GetShortURL(string _url, string tokenPass)
The rest is just like the method body of the first approach.
With the following url
http://...//GetShortURL/https%3A%2F%2Fgithub.com%2FVahidN%2FDNTPersianUtils.Core/TokenPass
The value of _url will be:
If you want to convert it to a correct url,you needs to replace %2F with / in GetShortURL:
var url = _url.Replace("%2F","/");
just make parameters to be optional
[HttpGet("GetShortURL/{_url?}/{tokenPass?}")]
public ActionResult<ServiceResult<string>> GetShortURL(string _url, string tokenPass)
in this case you can call the action without any parameters, with one parameter or with two parameters

Separating a part of the current URL

I want Separating a part of the current URL
Example:localhost:50981/Admin/AddCustomer.aspx
The part I want: AddCustomer
or
Example:localhost:50981/Request/Customer.aspx
The part I want: Customer
You can use AbsolutePath in your onLoad function of page.
//AddCustomer or Customer
string yourPath = HttpContext.Current.Request.Url.AbsolutePath.Split('/').Last().Split('.')[0];
You can make use of string.Split():
var url = "localhost:50981/Admin/AddCustomer.aspx";
var result = url.Split('/').Last().Split('.')[0];
To get the current Url path in Asp.Net:
var url = HttpContext.Current.Request.Url.AbsolutePath;
Note:
If you are interested in how to get the different parts of an url have a look at this answer:
var scheme = Request.Url.Scheme; // will get http, https, etc.
var host = Request.Url.Host; // will get www.mywebsite.com
var port = Request.Url.Port; // will get the port
var path = Request.Url.AbsolutePath; // should get the /pages/page1.aspx part, can't remember if it only get pages/page1.aspx

How to build a Url?

Are there any helper classes available in .NET to allow me to build a Url?
For example, if a user enters a string:
stackoverflow.com
and i try to pass that to an HttpWebRequest:
WebRequest.CreateHttp(url);
It will fail, because it is not a valid url (it has no prefix).
What i want is to be able to parse the partial url the user entered:
Uri uri = new Uri(url);
and then fix the missing pieces:
if (uri.Port == 0)
uri.Port = 3333;
if (uri.Scheme == "")
uri.Scheme = "https";
Does .NET have any classes that can be used to parse and manipulate Uri's?
The UriBuilder class can't do the job
The value that the user entered (e.g. stackoverflow.com:3333) is valid; i just need a class to pick it apart. i tried using the UriBuilder class:
UriBuilder uriBuilder = new UriBuilder("stackoverflow.com:3333");
unfortunately, the UriBuilder class is unable to handle URIs:
uriBuilder.Path = 3333
uriBuilder.Port = -1
uriBuidler.Scheme = stackoverflow.com
So i need a class that can understand host:port, which especially becomes important when it's not particularly http, but could be.
Bonus Chatter
Console application.
From the other question
Some examples of URL's that require parsing:
server:8088
server:8088/func1
server:8088/func1/SubFunc1
http://server
http://server/func1
http://server/func/SubFunc1
http://server:8088
http://server:8088/func1
http://server:8088/func1/SubFunc1
magnet://server
magnet://server/func1
magnet://server/func/SubFunc1
magnet://server:8088
magnet://server:8088/func1
magnet://server:8088/func1/SubFunc1
http://[2001:db8::1]
http://[2001:db8::1]:80
The format of a Url is:
foo://example.com:8042/over/there?name=ferret#nose
\_/ \_________/ \__/\_________/\__________/ \__/
| | | | | |
scheme host port path query fragment
Bonus Chatter
Just to point out again that UriBuilder does not work:
https://dotnetfiddle.net/s66kdZ
If you need to ensure that some string coming as user input is valid url you could use the Uri.TryCreate method:
Uri uri;
string someUrl = ...
if (!Uri.TryCreate(someUrl, UriKind.Absolute, out uri))
{
// the someUrl string did not contain a valid url
// inform your users about that
}
else
{
var request = WebRequest.Create(uri);
// ... safely proceed with executing the request
}
Now if on the other hand you want to be building urls in .NET there's the UriBuilder class specifically designed for that purpose. Let's take an example. Suppose you wanted to build the following url: http://example.com/path?foo=bar&baz=bazinga#some_fragment where the bar and bazinga values are coming from the user:
string foo = ... coming from user input
string baz = ... coming from user input
var uriBuilder = new UriBuilder("http://example.com/path");
var parameters = HttpUtility.ParseQueryString(string.Empty);
parameters["foo"] = foo;
parameters["baz"] = baz;
uriBuilder.Query = parameters.ToString();
uriBuilder.Fragment = "some_fragment";
Uri finalUrl = uriBuilder.Uri;
var request = WebRequest.Create(finalUrl);
... safely proceed with executing the request
You can use the UriBuilder class.
var builder = new UriBuilder(url);
builder.Port = 3333
builder.Scheme = "https";
var result = builder.Uri;
To be valid a URI needs to have the scheme component. "server:8088" is not a valid URI. "http://server:8088" is. See https://www.rfc-editor.org/rfc/rfc3986

asp:hyperlink navigate url adding relative path to the url

I have a Asp:Hyperlink in aspx page and i am setting the text and navigation url dynamically but when page renders it adds the relative path of my website in the rendered href. i dont know why?
ASPX
<asp:HyperLink runat="server" ID="charityNameText"></asp:HyperLink>
CODE-BEHIND (Page Load Event)
//Getting data from database
charityNameText.Text = entryDetails.RegisteredCharityName;
charityNameText.NavigateUrl = "www.facebook.com";
charityNameText.Target = "_blank";
Rendered HTML
<a id="ctl00_PageContent_CompetitionsEntries_ctl06_charityNameText" href="../../ConLib/Custom/www.facebook.com" target="_blank">save the childrens</a>
../../ConLib/Custom/ is the path where this file is located.
Plase help
There are different solutions for your case.
My best approach would be using the System.UriBuilder class.
String myUrl = "www.facebook.com";
UriBuilder builder = new UriBuilder(myUrl);
charityNameText.NavigateUrl = builder.Uri.AbsoluteUri;
The UriBuilder adds the protocol (HTTP) in your case to the URL you are loading and initializes an instance of the Uri class with the complete URL. Use the AbsoluteUri property.
For more complex cases you can use Regex :
String myUrl = "www.facebook.com";
System.Text.RegularExpressions.Regex url = new System.Text.RegularExpressions.Regex(#"/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
System.Text.RegularExpressions.MatchCollection matches = url.Matches(myUrl);
foreach (System.Text.RegularExpressions.Match match in matches)
{
string matchedUrl = match.Groups["url"].Value;
Uri uri = new UriBuilder(matchedUrl).Uri;
myUrl = myUrl.Replace(matchedUrl, uri.AbsoluteUri);
}
You have to add the protocol to the beginning of the URL:
http://wwww.facebook.com
I think you should use http://www.facebook.com
Hope that helps

Get anything after first slash in URL

I can get my browser url using : string url = HttpContext.Current.Request.Url.AbsoluteUri;
But say if I have a url as below :
http://www.test.com/MyDirectory/AnotherDir/testpage.aspx
How would I get the "MyDirectory" part of it, is there a utility in .NET to get this or do I need string manipulation ?
If I do string manipulation and say anything after first instance of "/" then wouldnt it return the slash after http:? It would work if my url was www.test.com/MyDirectory/AnotherDir/testpage.aspx
Can someone please help
Instantiate a Uri instance from your url:
Uri myUri = new Uri("http://www.test.com/MyDirectory/AnotherDir/testpage.aspx");
You can then get the path segments into a string array using:
string[] segments = myUri.Segments
Your first "MyDirectory" folder will be at:
string myFolderName = segments[0];
You can get this by PathAndQuery property of Url
var path = HttpContext.Current.Request.Url.PathAndQuery;
it will return /MyDirectory/AnotherDir/testpage.aspx
Uri uriAddr = new Uri("http://www.test.com/MyDirectory/AnotherDir/testpage.aspx");
var firstSegment= uriAddress.Segments.Where(seg => seg != "/").First();

Categories