How to Get the Absolutepath Without the Id or Query? - c#

Let's say my url is "https://www.mywebsite.com/app/company/employees/5" or "https://www.mywebsite.com/company/employees?id=5&name=jack"
I'm looking for a way to get the "base" path, or whatever it's called. Like the "base" path would be "/app/company/employees" for both, without the "/5" part or "?id=5&name=jack" part.
I was using string.Join("/", request.ApplicationPath, request.RequestContext.RouteData.Values["controller"], request.RequestContext.RouteData.Values["action"]) to get it (request is HttpRequestBase), but it doesn't work the way I want since it includes the Index action too. Like if the Url is "https://www.mywebsite.com/app/company" I want "/app/company/" not "/app/company/Index". I can always check if the action is Index or not but it feels like kind of a "code smell" to me.
Is it even a code smell? Is there any proper way to accomplish this?

The Uri Class offers many properties https://learn.microsoft.com/en-us/dotnet/api/system.uri?view=netframework-4.7.2
Try this
string val = HttpContext.Current.Request.Url.AbsolutePath;
or in your case if your request variable is an HttpRequest object, try:
string val = request.Url.AbsolutePath;

Use HttpContext.Current.Request.Url.AbsolutePath

Related

Is it better to use Uri.Absolute or the original string after Uri.TryCreate code execution?

In the code Uri.TryCreate(link, UriKind.Absolute, out testurl) the link is tested if valid and gives a Uri object for it. Should I then use original string link or string testurl.AbsoluteUri ? because both seem to have same string value after code execution.
You can use any. But the Uri object can give you more details about the url like Host, Scheme etc.
If there is no difference, it doesn't matter. Basically, you are just using the TryCreate to validate your URL, so using the original string should be just fine.
You should check for the result of TryCreate and use the resulting object if successful, otherwise fail gracefully; if it's purely for validation and the input and output are equivalent (if 'correct') then this is a non-issue.

Regular expression to get the Name from URL link

I have a Hyperlink field (aka column) in SharePoint 2010.
Say it's called SalesReportUrl. The url looks like:
http://portal.cab.com/SalessiteCollection/October2012Library/Forms/customview.aspx
The hyperlink field stores values in two fields (the link and description).
What would be the RegEx if I want to get the October2012Library out of the Url?
I tried this but it's definitely not working:
#"<a[\s]+[^>]*?href[\s]?=[\s\"\']+(.*?)[\"\']+.*?>([^<]+|.*?)?<\/a>";
I also tried:
^(.*?/)?Forms/$
but no luck.
I think sharepoint stores hyperlink like this:
http://portal.cab.com/SalessiteCollection/October2012Library/Forms/customview.aspx, some description
Looks like this has a solution. but what's the syntax substring get the list or library name ?https://sharepoint.stackexchange.com/questions/40712/get-list-title-in-sharepoint-designer-workflow
How about this (as Daniel suggested) :
string url = #"http://portal.cab.com/SalessiteCollection/October2012Library/Forms/customview.aspx";
Uri uri = new Uri(url);
if(uri.Segments.Length > 2))
Console.WriteLine(uri.Segments[2]); // will output "October2012Library/"
you can add .Replace("/", string.Empty) if you want to get rid of the "/"
Console.WriteLine(uri.Segments[2].Replace("/", string.Empty));
http://[^/]+/[^/]+/([^/]+)/
match's group[1] is the value you need. it gets the 3rd part (divided by /) in the url. if you need make sure it is followed by other parts, i.e. forms, add it at the end.
try using this new RegEx("SalessiteCollection/(.+?)/Forms").match(<urlString>).groups[1].value
Though it is a rough answer, you might have to make few corrections but I hope you understand what I am trying to explain.
maybe this?
http:\/\/([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}\/[a-zA-Z]*\/([a-zA-Z0-9]*)\/
http://rubular.com/r/LuuuORPRXt

Get value from string formed as URL in ASP.NET

Ok, I have a string of the form
string temp = "http://www.example.com?file=666111&submitter=Betty&origin=Office&telNo=05555";
what I need to do is extract the value of the file variable in order to use it. If this was the referrer url I could've done Request.QueryString and got it but the problem is that I have it as a string variable.
I could try to do substring and get the value but I was hoping there was a cleaner way to do this?
Perhaps you can use the HttpUtility.ParseQueryString method. It returns a NameValueCollection with all parameters.

How do I parse and rebuild a URL in ASP.Net?

I'm devloping a C#/ASP.Net app and I'm trying to find a means of breaking down a URL into its component parts, then swapping out, or deleting these parts and creating a new URL.
For example if I have the following URL:
https://www.site.com/page.aspx?parm1=value1&parm2=value2
I'd like to split the URL down into:
Protocol (http, https, ftp, etc)
Domain (www.site.com)
Page (page.aspx)
URL parameters (parm1 = value1, parm2 = value2)
Once the URL is split down I'd like to manipulate each of the parts, for example:
add or remove parameters
change the value of parameters
change the page from page.aspx to page2.aspx
Then once I'm done create a new URL ready for use with the above changes.
I've checked out the MSDN documentation etc and can't find a utility class in .Net to take care of this. Any ideas?
Cheers,
Steve
The framework comes with the UriBuilder class for this purpose.
It has get/set properties for the things you need:
Protocol: Scheme property
Domain: Host property
Page: Path property (will give you whole path, you might need to do some processing here).
Parameters: Query property (exposed as a string, you might need to do some processing on the string your self).
When you are done manipulating the UriBuilder, use the Uri property to get the result as a Uri object, or just ToString() if you just need the URL as a string.
Start by using UriBuilder (see driis's answer).
To parse the Query property use:
NameValueCollection q=HttpUtility.ParseQueryString(uri.Query);
You actually get an HttpValueCollection (internal) - so when you later call q.ToString() you'll get an url encoded query string back.
Since the class is internal you need to call
NameValueCollection q=HttpUtility.ParseQueryString("");
if you want to build the query string from scratch.

How do I use a pattern Url to extract a segment from an actual Url?

If I have a series of "pattern" Urls of the form:
http://{username}.sitename.com/
http://{username}.othersite.net/
http://mysite.com/{username}
and I have an actual Url of the form:
http://joesmith.sitename.com/
Is there any way that I can match a pattern Url and in turn use it to extract the username portion out the actual Url? I've thought of nasty ways to do it, but it just seems like there should be a more intuitive way to accomplish this.
ASP.NET MVC uses a similar approach to extract the various segments of the URL when it is building its routes. Given the example:
{controller}/{action}
So given the Url of the form, Home/Index, it knows that it is the Home controller calling the Index action method.
Not sure I understand this question correctly but you can just use a regular expression to match anything between 'http://' and the first dot.
A very simple regex will do:
':https?://([a-z0-9\.-]*[a-z0-9])\.sitename\.com'
This will allow any subdomain that only contains valid subdomain characters. Example of allowed subdomains:
joesmith.sitename.com
joe.smith.sitename.com
joe-smith.sitename.com
a-very-long-subdomain.sitename.com
As you can see, you might want to complicate the regex slightly. For instance, you could limit it to only allow a certain amount of characters in the subdomain.
It seems the the quickest and easiest solution is going off of Machine's answer.
var givenUri = "http://joesmith.sitename.com/";
var patternUri = "http://{username}.sitename.com/";
patternUri = patternUri.Replace("{username}", #"([a-z0-9\.-]*[a-z0-9]");
var result = Regex.Match(givenUri, patternUri, RegexOptions.IgnoreCase).Groups;
if(!String.IsNullOrEmpty(result[1].Value))
return result[1].Value;
Seems to work great.
Well, this "pattern URL" is a format you've made up, right? You basically you'll just need to process it.
If the format of it is:
anything inside "{ }" is a thing to capture, everything else must be as is
Then you'd just find the start/end index of those brackets, and match everything else. Then when you get to a place where one is, make sure you only look for chars such that they don't match whatever 'token' comes after the next ending '}'.
There are definitely different ways - ultimately though your server must be configured to handle (and possibly route) these different subdomain requests.
What I would do would be to answer all subdomain requests (except maybe some reserved words, like 'www', 'mail', etc.) on sitename.com with a single handler or page (I'm assuming ASP.NET here based on your C# tag).
I'd use the request path, which is easy enough to get, with some simple string parsing/regex routines (remove the 'http://', grab the first token up until '.' or '/' or '\', etc.) and then use that in a session, making sure to observe URL changes.
Alternately, you could map certain virtual paths to request urls ('joesmith.sitename.com' => 'sitename.com/index.aspx?username=joesmith') via IIS but that's kind of nasty too.
Hope this helps!

Categories

Resources