I want to remove ".aspx" from my web appliaction url. also I have using webservices.
If I use below code web services is not working.
Global.asax
protected void Application_BeginRequest(object sender, EventArgs e)
{
String WebsiteURL = Request.Url.ToString();
String[] SplitedURL = WebsiteURL.Split('/');
String[] Temp = SplitedURL[SplitedURL.Length - 1].Split('.');
// This is for aspx page
if (!WebsiteURL.Contains(".aspx") && Temp.Length == 1)
{
if (!string.IsNullOrEmpty(Temp[0].Trim()))
Context.RewritePath(Temp[0] + ".aspx");
}
}
for Eg:-
Actual page is DEFAULT.aspx, but I want to show DEFAULT in address bar. So I used Global.asax to remove (.aspx). It's working fine. but Web service is not working(Default.asmx)
There is a module that will handle this for you without having to directly manipulate the urls, as described here: http://www.hanselman.com/blog/IntroducingASPNETFriendlyUrlsCleanerURLsEasierRoutingAndMobileViewsForASPNETWebForms.aspx.
Install the package, Microsoft.AspNet.FriendlyUrls.
In your RouteConfig, the extensionless urls are enabled using:
routes.EnableFriendlyUrls();
You can generate friendly urls using extension methods, for example, to generate /Foo/bar/34, you can use:
Click me
Related
I published the web site and uploaded it to FTP (ASP.NET Web Forms C#).
I use routing in the project and this is my routing page's code (I only write 1):
protected void Application_Start(object sender, EventArgs e)
{
RegisterRoutes(RouteTable.Routes);
}
public void RegisterRoutes(RouteCollection routes)
{
routes.MapPageRoute("HomePage", "HomePage", "~/Views/Default.aspx");
}
And my folders and pages are as follows:
The code of the Default.aspx page outside the Views folder:
protected void Page_Load(object sender, EventArgs e)
{
Response.Redirect("/Views/");
}
When I try to enter mywebsite.com and enter the site, I get the following error:
But when I try to enter mywebsite.com/HomePage it works. I want to go to the main page when I write the site name directly. Where do I make mistakes?
I forgot to add: It's working on local btw. But doesn't work on FTP.
You have your routing configured incorrectly. The the home page URL is setup as HomePage instead of an empty string (/HomePage).
routes.MapPageRoute("HomePage", "HomePage", "~/Views/Default.aspx");
Change that to (/):
routes.MapPageRoute("HomePage", "", "~/Views/Default.aspx");
Also, delete your "Default.aspx page outside of Views folder". That is going to conflict with your routing and (even worse) it will cause an HTTP 302 redirect to your home page. An HTTP 302 redirect returned from the request tells the user's browser to make a second request to your server, which is bad for both performance and SEO reasons.
Given that your /HomePage URL is working correctly, the above changes should fix your problem.
We are using an application that runs on asp.net and C#. When a user is logged in, their profile information is displayed (name, id number) on a Profile page (information comes from MSSQL). I would like to get the id number for the logged in user and pass that value to an embedded form (this part I know I can do), the struggle is figuring out how to get the id number from one page to the other page.
I am not proficient with C# or asp.net but I did find where the id value is at, I am not sure how to call it from my form page?
Pass Values Between ASP.NET Web Forms Pages
The following options are available even if the source page is in a different ASP.NET Web application from the target page, or if the source page is not an ASP.NET Web Forms page:
Use a query string
Get HTTP POST information from the source page
The following options are available only when the source and target pages are in the same ASP.NET Web application:
Use session state
Create public properties in the source page and access the property
values in the target page
Get control information in the target page from controls in the
source page
The main factor that should influence your approach should be the fact that this is a secure application and you do not want the information being passed to be prone to scrutiny.
First Option:
Use Cookies
On your firstPage.aspx
HttpCookie appCookie = new HttpCookie("IdValue");
appCookie.Value = "The value of your id here" or id.ToString();
appCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(appCookie);
To get:
SecondPage.aspx
HttpCookie aCookie = Request.Cookies["IdValue"];
String getValue = aCookie.Value.ToString();
Cookies expires depends on your Settings here appCookie.Expires = DateTime.Now.AddDays(1); it can be AddDays('MoreNumberofdays') like AddDays(4) it will expires in 4 days. Something like that.
some additional Guide
Second Option:
Class:
public class Class1
{
public static string storevalue;
}
Page1.aspx
protected void Page_Load(object sender, EventArgs e)
{
Class1.storevalue = "This is the value from page1";
Response.Redirect("WebForm2.aspx");
}
Page2.aspx
protected void Page_Load(object sender, EventArgs e)
{
string getvalue = Class1.storevalue;
}
I have been tasked with giving my company's website (~40 pages) a facelift. The original site is written in straight html/css/javascript and every file has the .htm extension. The new site is written in .net 3.5, Hosted on windows through iis.
I am not changing the directoy structure at all, but every page will go from a .htm extension to .aspx and I am concerned about how this will effect my SEO.
From another SO question I found a link to this article detailing a custom http module from which I have the following code:
public class PermanentRedirectHttpModule : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
}
void context_BeginRequest(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
HttpRequest request = context.Request;
if (request.Url.PathAndQuery.Contains(".htm"))
{
string url = request.Url.ToString();
url = url.Replace(".htm", ".aspx");
context.Response.Status="301 Moved Permanently";
context.Response.AddHeader("Location", url);
context.Response.End();
}
}
}
I have implemented this method and everything works as I would expect it to. Is this method acceptable and will it maintain my search engine rankings?
This would work by redirecting all of your .htm paths to .aspx. Because you're doing a 301 redirect, you might notice a temporary drop in search engine places as the power gets transferred. You'll also need to make sure that any links on your site go to the new URLs, otherwise you'll get alot of internal 301 redirects.
An alternative would be to use URL rewriting. This way you could maintain your .htm URLs, but they would be rewritten to point to the .aspx pages.
Helicon ISAPI (http://www.isapirewrite.com/) is one I often use. If you just have the 1 site on the server, you can get away with using the lite (free) version.
If you're using IIS7, you could use the built in rewrites which are configured in the web.config file of your site.
I need to redirect a user to a different page if they visit a certain set of pages in a web. There is one condition: I'm not allowed to touch the IIS. I have googled around and found a thing called the custom HttpHandler for WSS 3.0. It sounded like something that I can use to capture the URL the user enters (the most malicious way to get to a page that should really be redirected) and redirect them to another page/web. But having not have the chance to use it yet, I was wondering am I on the right track by using a Custom HttpHandler to redirect a user to a different page in Sharepoint using C#?
Many thanks.
HttpHandlers are used by IIS to "handle" different document types, for instance you have separate .asmx handle, .aspx handler, .ascx handler, etc.
Look into SPUtility.Redirect
You can use the SPUtility.Redirect method whenever you want to direct the user to a different page. For example, you might create a landing page that determines the user's role membership, and based on that information you can redirect them to an appropriate page. Or, based on the contents of a query string issued by the user's browser, you might redirect them to a page that can process the query string, such as the Search Center results page.
Alternatively, you can look into Using Disposable Windows SharePoint Services Objects.
--EDIT--
This is in response to your comment; you are thinking in the right direction
Create a custom HttpHandler; Example 1, Example 2
Whenever a user requests a url, your custom HttpHandler is going to process that.
Redirect() if you like the url, else otherwise.
But for your Custom HttpHandler to work, it should be called first - so in your config file you will have to provide the value in path. Usually an extension is added here. But you can replace that with a * to work for all request. I believe that would work.
<httpHandlers>
<add verb="*" path="*.aspx" type="MyNameSpace.MyHttpHandler, MyAssemblyName" />
</httpHandlers>
--EDIT--
This is in response to your comment. Assuming that you have "access" to pages so that you can write javascript in it, you can use the javascript in following way.
<script language=JavaScript>
function RedirectIfUnAuthorized()
{
//Get the location of the current page.
var currentUrl = new String( document.location.href )
//See if it belongs to the urls you are looking for; redirect if so.
if (currentUrl == "http://www.thisUrl.com/page1.aspx") {Response.Redirect("http://www.GOOGLE.com")}
if (currentUrl == "http://www.thisUrl.com/page2.aspx") {Response.Redirect("http://www.BING.com")}
if (currentUrl == "http://www.thisUrl.com/page3.aspx") {Response.Redirect("http://www.someother.com")}
}
</script>
You may call the above javascript in the page's OnLoad event.
Are you allowed to deploy code on the server? Or is that touching IIS too?
(SharePoint makes changes to web.config too. If you're allowed to deploy code, so could you. If you don't tell your admins they probably wouldnt even notice.)
You can 'deploy' your web.config changes through an SPWebConfigModification and deploy any web.config redirections or httphandlers that way.
HTTP handlers are the end point
objects in ASP.NET pipeline and an
HTTP Handler essentially processes the
request and produces the response. For
example an ASP.NET Page is an HTTP
Handler.
HTTP Modules are objects which also
participate the pipeline but they work
before and after the HTTP Handler does
its job, and produce additional
services within the pipeline (for
example associating session within a
request before HTTP handler executes,
and saving the session state after
HTTP handler has done its job, is
basically done by an HTTP module,
SessionStateModule)
In your case, HTTPModule will require to redirect the another web page.
using System;
using System.Web;
using System.Web.UI;
using System.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data;
namespace CustomHttpModule
{
public class HttpModuleImplementation : IHttpModule
{
#region IHttpModule Members
public void Dispose()
{
}
public void Init(HttpApplication context)
{
if (context == null)
throw new ArgumentNullException("Context == null");
context.AuthorizeRequest += new EventHandler(this.ProcessRequestHandler);
}
#endregion
private void DummpRequest(object sender, EventArgs e)
{
}
//first check that user.identity record exist in database
//If not then forward user to User registration page
private void ProcessRequestHandler(object sender, EventArgs e)
{
try
{
HttpApplication context = (HttpApplication)sender;
string strAbsoluteUri = context.Request.Url.AbsoluteUri.ToLower();
//check if request is accessing aspx page
if (strAbsoluteUri.Substring(strAbsoluteUri.Length - 5, 5).Contains(".aspx"))
{
string userName = context.User.Identity.Name;
//replace Test Module with DB call to validate user data
if (!CheckUserInDb(userName))
{
if (!strAbsoluteUri.Contains("mypage.aspx"))
redirectToRegistrationPage(context);
}
}
}
catch (Exception ex)
{
}
}
private void redirectToRegistrationPage(HttpApplication context)
{
context.Response.Redirect("http://" + context.Request.ServerVariables["HTTP_HOST"].ToString() + "Regpage.aspx", false);
}
private bool CheckUserInDb(string userName)
{
return true;
}
}
}
In SharePoint virtual directory web.config file you have to enter the following entry under section httpModules :
<add name="CustomHttpModule" type="CustomHttpModule.HttpModuleImplementation, CustomHttpModule" />
Objective was:
To change pages like details.aspx?GUID=903901823908129038 to clean ones like /adrian_seo
Achieved:
Now using Response.AddHeader("Location", url);
I am able to remove all uppercase urls. I use the following function:
protected void Page_Load(object sender, EventArgs e)
{
string url = Request.Url.ToString();
if (url != Request.Url.ToString().ToLower())
{
url = Request.Url.ToString().ToLower();
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location", url);
}
}
Question is:
How do I change these to clean urls like /adrian_seo
I mean how do I handle requests coming to /adrian_seo and how do I show my old pages with new urls.
Do I need to use Global.asax?
Have a look into ASP.NET routing.
Use an HttpModule:
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
}
void context_BeginRequest(object sender, EventArgs e)
{
HttpContext context = ((HttpApplication)sender).Context;
if (context.Request.RawUrl.ToLowerInvariant().Equals("YOURSEOURL"))
context.RewritePath("YOURNONSEOURL");
}
Note that you don't want to hard code all this. Find some sort of regex to match your need, like if the SEO url is: /page/234234/This-is-my-page-title, you grab the 234234 and rewrite the path to page.aspx?pageid=234234
UPDATE
You can also use the IIS 7 Rewrite Module
I recommend using the UrlRewritingNet component. When writing your own library you need to overcome some difficulties, this library already handles that stuff for you...
It is a rewrite-module tuned for
ASP.NET 2.0, and offers support for
Themes and Masterpages
Regular Expressions
Good Postback-Urls
Cookieless Sessions
Runs in Shared-Hosting or Medium-Trust enviroments
OutputCache is supported
Redirects possible, even to other Domains
To enable extenionless urls in asp.net with IIS 6 or lower your also need to configure IIS to let asp.net handle all incoming requests.
You could use http://urlrewriter.net/ which can be used on asp.net 1.1 ->
After some Read up on Routing in Asp.net:
http://blog.eworldui.net/post/2008/04/ASPNET-MVC---Legacy-Url-Routing.aspx
Which brings both 301 redirects for SEO page rank and Asp.net Routing for permanent organic SEO solution.