ASP.NET Web Forms Switch from Site.Mobile.Master - asp.net

I have an ASP.NET 4.5 Web Forms Application utilizing Bootstrap. http://goo.gl/GZZp9r
I had a problem whereby Site.Mobile.Master was being utilized whenever the website was being rendered in Extra Small ViewPort. Since using Bootstrap I did not need this Site.Mobile.Master.
I had implemented a solution that would cause Site.Mobile.Master to not render, instead only utilizing Site.Master.
public partial class Site_Mobile : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
var AlternateView = "Desktop";
var switchViewRouteName = "AspNet.FriendlyUrls.SwitchView";
var url = GetRouteUrl(switchViewRouteName, new { view = AlternateView, __FriendlyUrls_SwitchViews = true });
url += "?ReturnUrl=" + HttpUtility.UrlEncode(Request.RawUrl);
Response.Redirect(url);
}
}
The above solution is causing problem with GoogleBot because of 302 Redirects.
Someone has indicated that:
"when the user agent is Google mobile when your homepage is requested your site responds with a 302 redirect to
/__FriendlyUrls_SwitchView?ReturnUrl=/
and then the request is 302 redirected again to /
I have read that I cannot simply delete Site.Mobile.Master.
Is there a better solution to NOT render this Site.Mobile.Master for Extra Small ViewPort?

I'm not sure what the benefit would be to use this solution.
But hopefully this would resolve 302 Redirects that is bad for GoogleBot.
<browserCaps>
<result type="System.Web.Mobile.MobileCapabilities, System.Web.Mobile, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
<filter>isMobileDevice=false</filter>
</browserCaps>

Related

How to ignore some route while using ASP.NET Friendly URLs?

I am using ASP.NET Friendly URLs with success, but I need to ignore route for a particular Foo.aspx page (because this page needs POST data and once re-routed the POST data is not available anymore in Page_Load()!).
It looks like using ASP.NET Friendly URLs discard any attempt to ignore a route. Even the MSDN example for ignoring route doesn't work once ASP.NET Friendly URLs routing is used:
routes.Ignore("{*allaspx}", new {allaspx=#".*\.aspx(/.*)?"});
And to ignore route to Foo.aspx the code should look like that, isn't it?
routes.Ignore("{*fooaspx}", new { fooaspx = #"(.*/)?foo.aspx(/.*)?" });
The Global.asax code looks like:
public static void RegisterRoutes(RouteCollection routes) {
// This doesn't work whether I put this code before or after ASP.NET Friendly URLs code.
routes.Ignore("{*allaspx}", new { allaspx = #".*\.aspx(/.*)?" });
routes.Canonicalize().Lowercase();
var settings = new FriendlyUrlSettings();
settings.AutoRedirectMode = RedirectMode.Permanent;
routes.EnableFriendlyUrls(settings);
}
void Application_Start(object sender, EventArgs e) {
RegisterRoutes(RouteTable.Routes);
}
This question has been asked on the ASP.NET Friendly URLs codeplex site, but didn't get an answer.
Thanks for your help on this :)
Thanks to Damian Edwards comment, I got this issue completely solved, thanks Damian.
I just need to derive from WebFormsFriendlyUrlResolver to override the method ConvertToFriendlyUrl() to make it no-op when the url match the url I don't want to redirect:
using Microsoft.AspNet.FriendlyUrls.Resolvers;
public class MyWebFormsFriendlyUrlResolver : WebFormsFriendlyUrlResolver {
public MyWebFormsFriendlyUrlResolver() { }
public override string ConvertToFriendlyUrl(string path) {
if (!string.IsNullOrEmpty(path)) {
if (path.ToLower().Contains("foo")) { // Here the filter code
return path;
}
}
return base.ConvertToFriendlyUrl(path);
}
}
Then in Global.asax the code now looks like:
public static void RegisterRoutes(RouteCollection routes) {
routes.Canonicalize().Lowercase();
var settings = new FriendlyUrlSettings();
settings.AutoRedirectMode = RedirectMode.Permanent;
routes.EnableFriendlyUrls(settings,
new IFriendlyUrlResolver[] {
new MyWebFormsFriendlyUrlResolver() });
}
void Application_Start(object sender, EventArgs e) {
RegisterRoutes(RouteTable.Routes);
}
This was interesting - had to tinker :) In my comment above, what I was trying to say was "no need to ignore".
I was "right" and "wrong".
right: no need to ignore
wrong: not because of what I stated (re: physical file), but rather, by not invoking the redirect in the first place.
This will bomb out (redirect will occur, POST data is lost):
<asp:Button ID="btn1" runat="server" Text="Go" PostBackUrl="~/Target.aspx" />
This will be good (you will get POST data, no redirect occurs):
<asp:Button ID="btn1" runat="server" Text="Go" PostBackUrl="~/Target" />
The difference? I'm not asking FriendlyUrls to "re-route" anything in the 2nd option. In the first option, I'm asking for an "aspx" file, so FriendlUrls will dutifully do its purpose for being and "handle" it (and do a permanent redirect to a "friendly url" which is a GET and there goes all the POSTed data).
Inspect request in 1st option (target.aspx):
Inspect request in 2nd option (extensionless, target):
This was a clue:
var settings = new FriendlyUrlSettings();
settings.AutoRedirectMode = RedirectMode.Permanent;
And it does what it says, "do a permanent redirect" (to a "friendly url")...when "necessary" (if an "aspx" file is requested). You can tinker with this with any page in your WebForms site
if you request foo.aspx you will see a Redirect (to foo)
if you request foo, no Redirect
You can also comment out
settings.AutoRedirectMode = RedirectMode.Permanent;
and things will work but sort of defeats the purpose of FriendlyUrls...
Thinking about it, it makes perfect sense. There is no need to "redirect" on every request (ugh for performance), rather only if/when necessary...
Hth....

Redirect from page1 to page2, two questions

I have a my-site.ru/page1.apsx which will be a part of my-site.ru/page2.aspx so I need to rewrite (or redirect ?) page1.aspx to page2.aspx
I added this to my web.config:
<system.web>
<urlMappings enabled="true">
<add url="~/page1.aspx" mappedUrl="~/page2.aspx"/>
</urlMappings>
</system.web>
The only thing I don't know hot to fix is: why text in address bar is my-site.ru/page1.aspx but i see my-site.ru/page2.aspx ?? I want while redirecting (rewriting) text in address bar changes too.
Question2: How will it reflect on SEO of page1.aspx ? If possible, please, provide a link. i'm a SEO beginner.
PS: I'm not a native english speaker so there must be some errors.
if you are not going to need the content reflected on page1.aspx or if you are going to move the content to your page2.aspx, I would suggest you to do a 301 redirect, which is a a permanent redirect this will affect your seo passing all the SEO information to the page you´re doing the redirect which is page2.aspx in this case.
from the seo perspective other things you can do are:
- remove page1 from your xml sitemap (if you have any)
- Exclude the page from robots.txt
to perform a redirect either you can do it in IIS 7 (or above) you can include an element in your web.config like:
<httpRedirect enabled="true" exactDestination="true" httpResponseStatus="Permanent">
<add wildcard="/page1.aspx" destination="/page2.aspx" />
</httpRedirect>
or you can code the redirection and check for the url in each request like:
public class RedirectHttpModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(this.context_BeginRequest);
}
private void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
HttpContext context = application.Context;
//check here context.Request for using request object
if(context.Request.FilePath.Contains("page1.aspx"))
{
context.Response.RedirectPermanent("/page2.aspx");
}
}
}
if you are using .NET 4.0 or above take a look to the permament redirection
just be aware that if you perform a regular response.redirect you are doing a 302 redirect that will affect your seo.
on page load
Write this
server.transfer("Page2.aspx")

Extensionless SEO Friendly with Asp.net webforms

How to get extension less and without query string SEO friendly URL for asp.net web forms.?
I have found out a very good article Here
It is a very good blog post written on how to redirect urls which contain query strings as extension less seo friendly urls.
One method of doing it by including Global.asax into the application.
Here is the example.
Include Global.asax into the application.
<%# Import Namespace="System.Web.Routing" %>
inside global.asax file
void registerroute(RouteCollection routes)
{
routes.MapPageRoute(
"Home-Route",
"Home",
"~/Default.aspx"
);
}
Which will map the home page or default page
For Query string urls like http://xyz.com/page.aspx?id=about
routes.MapPageRoute(
"Page-Route",
"Pages/{page}",
"~/page.aspx"
);
Then call this registerroute() inside application start event under Global.asax
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
registerroute(RouteTable.Routes);
}
Then to access the query string inside pages.
string pg = Page.RouteData.Values["page"] as string;

How I can hide url

void Application_BeginRequest(Object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
if (app != null)
if (app.Request.AppRelativeCurrentExecutionFilePath == "~/About.aspx")
app.Context.RewritePath(
app.Request.Url.PathAndQuery.Replace("/About.aspx", "")
);
}
I want to hide url like the following :
requested url : "http://domain.com/WebFolder/page.aspx"
url should be show : "http://domain.com/WebFolder"
The above code is not producing my desired result. It's causing to redirect new rewrite page. I don't want that, I just want to hide my url for section of page name.
You can use the IIS URL Rewrite module.
I have two ways to accomplish this in mind.
One is making your page a default page under IIS.
To do this,you should select Properties page for your folder WebFolder under IIS then select default page ( default is index.html ) to your page (page.aspx),then make it top page.
Second is ISAPI Rewriting which is more useful.It is a free .dll.Look at this site for more information.
Hope this helps
Myra

Recursive redirect on error handler page

I use the following MSDN code on my master page to detect if the browser accepts cookies:
protected void Page_Load(object sender, EventArgs e)
{
if(!this.IsPostBack) {
if(Request.QueryString["CookieTest"] == null) {
Response.Cookies["TestCookie"].Value = "Test";
Response.Redirect("CookieCheck.aspx.redirect=" + Server.UrlEncode(Request.Url.ToString())));
}
else if((string)Request.QueryString["Test"] == "passed") {
// my stuff...
}
}
}
The CookieCheck.aspx contains the following:
protected void Page_Load(object sender, EventArgs e)
{
if(Request.Cookies["TestCookie"] == null)
Response.Redirect(Request.QueryString["redirect"] + "?Test=notPassed", true);
else
Response.Redirect(Request.QueryString["redirect"] + "?Test=passed", true);
}
Within the web.config i have defined the following:
<customErrors mode="On" defaultRedirect="Error.aspx" />
Now the recognizing of the cookies works well, but I have this problem: Whenever an error occurs on the page and I should be redirected to Error.aspx (and this worked before the whole cookie detection thing), the redirection seems stuck in an infinite loop and appends more and more "?Test=passed" to the URL. I should mention that the Errors.aspx also has the same masterpage and thus also performs the cookie check. However I have no clue why the redirection doesn't stop. Is there a way to solve this problem other than to exlude the Errors.aspx page from having the master page? Thank you very much.
If the CookieCheck.aspx page also uses the same Master page it will keep redirecting recursively, make sure that CookieCheck.aspx is not using the same MasterPage.
I'd rather recommend not using MasterPages for this, Master Pages by design are for Visual Inheritance not code Inheritance, if you wish to make some special type of pages that checks for the the browser ability to use cookies, you can have a new base class for these pages
public abstract class CookieEnabledPage : Page
{
}
and add your logic to this class, then whenever you need to make a new page with this behavior you inherit from this base class. I think this is a much cleaner way of doing what you want.
I guess the masterpage (or the combination masterpage-error.aspx) is raising an exception which triggers a redirect to error.aspx, which in turn causes the masterpage to restart its lifecycle and raise a new exception. The concatenation of "?Test=passed" is almost certainly a side effect of reinvoking the cookie test every time an error redirect occurs.
I suggest firing up the debugger and setting a breakpoint at Page_Load in Masterpage.aspx.cs and step through until you are redirected to the error page (the last line which gets execued is the one raising the exception).

Resources