RouteCollection Querysting - asp.net

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);
}

Related

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.

ASP.NET if root URL contains query string, pass it to default.aspx on redirect

Is there any way that I can preserve a query string and pass it to the default.aspx;
For example:
http://www.example.com/?test=123
becomes
http://www.example.com/Default.aspx?test=123
Thanks in advance!
Yes you can. You could use Request.QueryString["test"] to get the value from query string and pass it to the other page using
if(Request.QueryString["test"] != null)
{
Response.Redirect("~/Default.aspx?test=" + Request.QueryString["test"].ToString())
}
Do this in Session_Start method of Global.asax.cs
Or if you want to pass the entire query string instead of one value just use Request.QueryString.ToString()

Check if string matches url

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"

ASP.NET Routing - With and without a slash at the end

Considering the following Service Contract:
[WebGet(UriTemplate = "/stores")]
DTO.Stores GetAllStores();
[WebGet(UriTemplate = "/stores/{name}")]
DTO.Stores GetStores(string name);
I can reach these two Urls: http://localhost/v1/stores and http://localhost/v1/stores/Joe. However the Url http://localhost/v1/stores/ (notice the slash at the end) returns me an "Endpoint not found" error. Ideally, I would like http://localhost/v1/stores/ to call GetAllStores().
How can I do that? Thanks!
I would try putting a tilde in. Perhaps "~/stores"?
Or, with routing, drop the "/" at the front.
What if you use "string? name" as parameter?
[WebGet(UriTemplate = "/stores/{name}")]
DTO.Stores GetStores(string? name);
And since both methods you have are returning the same thing (DTO.Stores) you could use a single method to get the Stores instead of two (as you are doing now). Like this:
[WebGet(UriTemplate = "/stores/{name}")]
DTO.Stores GetStores(string? name)
{
if(string.IsNullOrEmpty(name))
{
//get specific store
}
else
{
//get all stores
}
}
P.S.: I am not sure if that would work well with WCF, but give it a try. ;-)

SEO: Duplicated URLs with and without dash "/" and ASP.NET MVC

after reading this article "Slash or not to slash" (link: http://googlewebmastercentral.blogspot.com/2010/04/to-slash-or-not-to-slash.html) on Google Webmaster Central Blog (the oficial one) I decided to test my ASP.NET MVC app.
For example:
http://domain.com/products and http://domain.com/products/ (with "/" in the end), return the code 200, which means: Google understands it as two different links and likely to be a "duplicated content". They suggest to choose the way you want... with or without dash and create a 301 permanent redirect to the preferred way.
So if I choose without dash, when I try to access http://domain.com/products/ it will return a 301 to the link without dash: http://domain.com/products.
The question is, how can I do that with ASP.NET MVC?
Thanks,
Gui
If your using IIS 7 you could use the URL Rewrite Extension ScottGu has a blog post about it here.
Alternatively if you want to do it in code you could inherit from PerRequestTask. Here some sample code the removes the www from an address - this is from Shrinkr:
public class RemoveWww : PerRequestTask
{
protected override TaskContinuation ExecuteCore(PerRequestExecutionContext executionContext)
{
const string Prefix = "http://www.";
Check.Argument.IsNotNull(executionContext, "executionContext");
HttpContextBase httpContext = executionContext.HttpContext;
string url = httpContext.Request.Url.ToString();
bool startsWith3W = url.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase);
bool shouldContinue = true;
if (startsWith3W)
{
string newUrl = "http://" + url.Substring(Prefix.Length);
HttpResponseBase response = httpContext.Response;
response.StatusCode = (int) HttpStatusCode.MovedPermanently;
response.Status = "301 Moved Permanently";
response.RedirectLocation = newUrl;
response.SuppressContent = true;
response.End();
shouldContinue = false;
}
return shouldContinue ? TaskContinuation.Continue : TaskContinuation.Break;
}
}
You would just need to check for the url ending with a / in your code.
** Note this does use a 3rd party dll - System.Web.MVC.Extensibility namespace. **
It dosnt matter really for Google, but what does matter is if both urls'
http://domain.com/products and http://domain.com/products/ show the same page, you also need to watch with windows servers that links to your site like from external pages where the user has typed http://domain.com/PRODUCTS/ will aloso be seen as a diffrent page as the web is case sensitive.
There is away round this with the use of canonical url meta tag, it tell s google what the page name is really, so will avoid duplicate pages which ant really diuplicate
http://googlewebmastercentral.blogspot.com/2009/02/specify-your-canonical.html
you need to check the URI in the INIT event and check the URI to see if it coming in with the slash, if it is, simply do a redirect and add the 301 header to the output response.

Resources