Check if string matches url - asp.net

I've got a string url e.g. "http://localhost:3839/MyController/Statement1/myResult"
I need to do some logic on this i.e. if the url contains MyController/ and /myResult I need to redirect somewhere else.
Whats the easiest way to do this? I'm trying with regex but not sure how to do this.

You can do like below
string strURL=#"http://localhost:3839/MyController/Statement1/myResult";
if(strURL.contains("MyController") || strURL.contains("myResult")
{
//redirect logic here
}

What you could do is create a new Uri instance, which will do the parsing for you. You can create an Uri instance for you URL as follows:
var uri = new Uri("http://localhost:3839/MyController/Statement1/myResult");
You can then use the properties of the Uri instance to extract the different parts of the URI:
Console.WriteLine(uri.AbsolutePath); // outputs "/MyController/Statement1/myResult"
Console.WriteLine(uri.Scheme); // outputs "http"
Console.WriteLine(uri.Host); // outputs "localhost"
Console.WriteLine(uri.Port); // outputs "3839"

Related

DNN rewriting URL and adding Default.aspx? in Query-String

I have a Product list page on DNN.
On this module I have a function which is called when clicked. I am adding the name of the product and SKU in the URL as a Querystring. I noticed that DNN would rewrite ?Title= to /Title/ as well as &SKU= to /SKU/ when the SKU is normal without a forward slash. For example SKU/SR2018B
The URL below would work:
www.ourwebsite.com/Product-View/Title/staple-remover-black/sku/SR2018B
My main problem is when the SKU has a special character like a forward slash, for example: SS023/10. This will cause the URL to break. I am using an encoder for the SKU. Notice that ?Title did not change to /Title/ and now there is a Default.aspx? present in the URL below.
www.ourwebsite.com/Product-View?Title/staples-2313-1000pcs-100-pages/Default.aspx?sku=SS023%2f13
Here is my Code Behind when a person is redirected to the Detailed Page.
if (tabIdToRedirectTo == null) m_alerts.ShowModuleMessage(ModuleMessage.ModuleMessageType.RedError, $"An error occurred when attempting to Redirect to the '{settingKey}' Page!", ref plcMessages, true); else Response.Redirect(Globals.NavigateURL(tabIdToRedirectTo.TabID, "", "?Title="+ hiddendescription.Value + "&sku=" + HttpUtility.UrlEncode(hiddensku.Value), EmbeddedModule.GenerateFullQueryStringForEmbedding(EmbeddedCompanyCode, EmbeddedShowCustPricing)));
I believe it's how you're calling the Globals.NavigateUrl function. The call takes a params of strings which are your query strings in the key=value format. I usually like to easily see what I am about to pass so I do something like the following:
var qsParams = new List<string>{
"Title=" + hiddendescription.Value, // "Title=staples-2313-1000pcs-100-pages"
"sku=" + HttpUtility.UrlEncode(hiddensku.Value), // "sku=SS023%2f13"
EmbeddedModule.GenerateFullQueryStringForEmbedding(EmbeddedCompanyCode, EmbeddedShowCustPricing)
};
return Globals.NavigateURL(tabIdToRedirectTo.TabID, "", qsParams.ToArray());
Granted - I do not know what your EmbeddedModule.GenerateFullQueryStringForEmbedding does, but as long as it returns a key=value type output, it should be passed and processed well.

URLs with slash in the middle of parameters

I am creating a MVC 4 application and using the route mapping to route a url like
http://ModelSearch.com/Home/PartDetail/1000-1583-XIR/a
routes.MapRoute("PartDetail", "{controller}/{action}/{id}/{rev}", new { action = "PartDetail" });
There might be id like "1000/1584"
http://ModelSearch.com/Home/PartDetail/1000/1584/b
How do I handle it from new mapRoute? wildcard doesn't work for middle parameter.
You can re arrange your parameter and use the wildcard url segments for Id at the end of your url pattern.
[Route("Home/PartDetail/{rev}/{*id}")]
public ActionResult PartDetail(string rev,string id)
{
return Content("rev:"+rev+",id:"+id);
}
The *id is like a catch anything. So "1000/1584" segment of the request url will be mapped to the id parameter.

Get string from current URL

I am writing an asp.net MVC Application. I have the application send a request to FreeAgent and if the request is successful a code is returned in the redirect of the URL.
For example this is a copy of a successful URL.
{
http://localhost:3425/FreeAgent/Home?code=144B2ymEKw3JfB9EDPIqCGeWKYLb9IKc-ABI6SZ0o&state=
}
They have added the ?code=144B2ymEKw3JfB9EDPIqCGeWKYLb9IKc-ABI6SZ0o&state= to my URL
I need the bit after the ?code= and before &state=
I can use this to get the URL
string code = Request.Url.AbsoluteUri;
but I need help extracting the code from this
edit:
The code will be different each time it is run
You can use the System.Uri and System.Web.HttpUtility classes
string uri = "http://localhost:3425/FreeAgent/Home?code=144B2ymEKw3JfB9EDPIqCGeWKYLb9IKc-ABI6SZ0o&state=";
string queryString = new System.Uri(uri).Query;
var queryDictionary = System.Web.HttpUtility.ParseQueryString(queryString);
Then the value of the code query parameter will be available in queryDictionary["code"]

Is there a way to assign an external URL to a HyperLink without appending http:// or https:// (ie, the protocol)?

I have a HyperLink defined like so:
<asp:HyperLink ID="hltest" runat="server"></asp:HyperLink>
In my code, I do this:
hltest.NavigateUrl = "www.google.com"
However, the actual link looks like this:
http://localhost:53305/www.google.com
I can append http:// to the URL, but this not the preferred method because this URL is maintainable by the user. If the user saves the URL as http://www.google.com then the URL will end up looking like http://http://www.google.com. I know that I can strip http:// from the URL and then add it back to ensure that it doesn't show up twice, but this is extra code/helper method that I would like to avoid writing.
Edit: This is the type of code I am trying to avoid having to write:
hltest.NavigateUrl = "http://" & "hTTp://www.google.com".ToLower().Replace("http://", String.Empty)
Update I know I specifically asked how to do this without appending the protocol to the URL, but it looks like there's just no other way to do it. The selected answer brought me to this solution:
Function GetExternalUrl(Url As String) As String
Return If(New Uri(Url, UriKind.RelativeOrAbsolute).IsAbsoluteUri, Url, "http://" & Url)
End Function
This is great because, if the user enters just www.google.com, it will append http:// to the URL. If the user provides the protocol (http, https, ftp, etc), it will preserve it.
Use the Uri class and handle it accordingly:
Uri uri = new Uri( userProvidedUri, UriKind.RelativeOrAbsolute );
if( !uri.IsAbsolute ) hltest.NavigateUrl = "http://" + userProvidedUri;
else hltest.NavigateUrl = userProvidedUri;

RouteCollection Querysting

I am trying to define MapPageRoute on the application global.asax but my problem is that I can not route the specific URL to a physical file with a query string.
For example I want to redirect http://mysite.com/Apple to http://mysite.com/product.aspx?id=95.
What I managed to achieve so far is if a user ask for ./Apple he will be redirected to ./product.aspx but I can not pass the query string.
Looking forward for your comments.
Try this:
if (Page.RouteData.Values["Apple"] != null)
{
int appleID = Convert.ToInt32(Page.RouteData.Values["Apple"]);
Response.Redirect("~/product.aspx?id=" + appleID.ToString(), true);
}

Resources