Url rewriting asp.net 3.5 - c#

I have implemented URL rewriting using Intelligencia, everything works perfectly.
now if i have an anchor i could do somenthig like
Test
with the seo friendly url olready in place
or do i have to do somenthing like
Test
public string GetSeoUrl(string url)
{
if(url == "../TestPage.aspx") return ../TestPage;
}
This will allow me to manage from a central location all the URLs.
I am working on .net 3.5 Web Form
But what are the implications of both approaches?Is it going to be slower?less efficient?is the right way to do it?
Thanks

I think second way is right way to do it. ( Managing from Central Location )
also,i don't think there will be any SEO implication using this as the final URL will be same but second one is rendred from server.
It might be littlebit slow but not noticable. as it runs some server code to generate url while first cenarion there won't be any processing.

I see you are using .NET, you can to do this already developed solution from ASP.NET MVC Framework called URL routing.
Read this http://weblogs.asp.net/scottgu/archive/2007/12/03/asp-net-mvc-framework-part-2-url-routing.aspx

I would do the first one. The URL is the contract. Using the second approach may make you think that you can easily change the URL by updating the function. Changing the URL would cause seo issues.

Related

Use razor/asp.net mvc3 to generate static html pages?

For one projet, I've to generate static .html pages, which are gonna to be published on a remote server.
I've to automate the creation of those files from a c# code, which takes data from a SQL Server database.
Data will be not often changed(every 4-5 month), and this website will be highly frequented.
Since I find the razor synthax of asp.net MVC3 very effective, I was wondering if it's possible to use asp.net MVC3/Razor to generate those .html pages?
So:
Is this a good idea?
If yes, what is the good way?
If you think to another good manner of doing it, which way?
Thank you for the help
Edit
Regarding answers, I need to make a precision: I don't want/need to use web caching, for a lot of reasons(load(millions of pages loaded every month), integration(we integrate our page in an optimized apache with, another part of a website), number of pages(caching will only help me if I've the same pages a lot of time, but I will have ~2500 pages, so with murphy's law, except if I put a very high cache timeout, I will have to generate them often). So I really search something to generate HTML pages.
Edit 2
I just got a new constraint :/ Those template must be localized. Meaning that I should have something equivalent to the following razor code: #MyLocalizationFile.My.MyValue
Edit 3
Currently, I'm thinking of doing a dynamic website, and call some http query on it, to store the generated HTML. BUT, is there a way to avoid the http? meaning simulate an http call, specifiy the output stream and the url called(with only GET call).
Our previous load numbers were really underestimated, actually they have a little more than one million visitor each days, ~ 14 million pages loads/day.
Yes it is. Even when you can cache the results, HTML pages will be always faster and use lower server resources
A good way is to transform your razor views into text and then save the text as a html file.
Another way can be using T4 templates, but I recommend Razor.
You can use the Razor Engine (NuGet-link, their website), This way you can create templates from a console application without using asp.net MVC.
I use it as follows:
public string ParseFile<T>(string fileName, T model) {
var file = File.OpenText(fileName);
var sb = new StringBuilder();
string line;
while ((line = file.ReadLine()) != null)
{
// RazorEngine does not recognize the #model line, remove it
if (!line.StartsWith("#model ", StringComparison.OrdinalIgnoreCase))
sb.AppendLine(line);
}
file.Close();
// Stuff to make sure we get unescaped-Html back:
var config = new FluentTemplateServiceConfiguration(
c => c.WithEncoding(RazorEngine.Encoding.Raw));
string result;
using (var service = new TemplateService(config))
{
return service.Parse<T>(sb.ToString(), model);
}
}
}
Rather than generating static HTML pages, I think it would be better to dynamically generate the pages each time, but using Caching to increase performance.
See this article on caching with ASP.NET MVC3 for more information:
http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/improving-performance-with-output-caching-cs
I ended by creating a normal asp.net MVC website and then generate page by going on the page with a WebClient.
Like this I can have a preview of the website and I can enjoy the full power of Razor+MVC helpers.
Is there any performance reason you've run into that would merit the effort of pre-rendering the website? How many pages are we talking about? What kind of parameters do your controllers take? If vanilla caching does not satisfy your requirements, for me the best approach would be a disk-based caching provider...
http://www.juliencorioland.net/Archives/en-aspnet-mvc-custom-output-cache-provider
Look at T4 templates or a similar templating solution
I'm working on a similar solution. My website is running normally (ASP.NET + DB + CMS) on a staging environment and then I use wget to crawl it and generate static html pages. Those static html pages, including assets are then uploaded to a Amazon S3 Bucket. That way the website becomes fully static, with no dependencies.
I'm planning to have a daily task that crawls specific pages on the website to make it speedier, e.g. only crawl /news every day.
I know you've already found a solution, but maybe this answer might be helpful to others.

Are Querystrings in .NET Good Practice?

I'm developing a web app that has a database backend. In the past I'm done stuff like:
http://page.com/view.aspx?userid=123 to view user 123's profile; using a querystring.
Is it considered good practice to use a querystring? Is there something else I should be doing?
I'm using C# 4.0 and ASP.net.
Your question isn't really a .NET question... it is a concern that every web framework and web developer deals with in some way.
Most agree that for the main user facing portion of your website you should avoid long query strings in favor of a url structure that makes "sense" to the website visitor. Try to use a logical hierarchy that when the visitor reads it there is a good chance they can deduce where they are on the site. Click around StackOverflow in a few areas and see what they have done with the url's. You usually have a pretty good idea what you're looking at and where you are.
A couple of other heads up... Although a lot of database lookups are done with the primary key it's also a good idea to provide a user friendly name of the resource in your url instead of just the primary key. You see StackOverflow doing that in the current address where they're doing the lookup with the primary key "3544483" but also including an SEO/user friendly url paramenter "are-querystrings-in-net-good-practice." If someone emailed you that link you'd have a pretty good idea of what you're about to open up.
I'm not really sure how WebForms handles Url Routing but if you're struggling to grasp the concepts go through the MVC NerdDinner tutorial. They cover some basic url routing in there that could help.
Query String are perfectly fine if you're sure to lock down what people are meant to view.. You should be checking for a valid value (number, not null, etc..) and if your application has security, whether a Visitor has permission to view User 1245's profile..
You could look into Session & ViewState, but QueryString seems to be what you're after.
If possible, I think this practice should be avoided especially if you're passing auto-incrementing ids in plain text. In my opinion, you're almost teasing the user to manipute the querystring value and see if they can get access to someone else's profile. Even with appropriate security measures in place (validating the request on the server-side before rendering the page), I would still recommend encrypting the querystring param in this particular case.
I think using query strings is perfectly fine, but there's a case to be made for hackable URLs, in that they are more understandable to advanced users and are SEO-friendly. For example, I happen think http://www.example.com/user/view/1234 looks more intuitive than http://www.example.com/view.aspx?user=1234.
And you don't have to alter your application to use pretty URLs if you're using IIS 7.0. The URL Rewrite Module and a few rewriting rules should be enough.
To answer clearly at your question: yes it't a good pratice. In fact it's an expected behavior of a web site.
I'm totaly agree with ShaderOp and you should use a url rewritter to get an nice loocking url. In fact I'm assuming that you will put a bit of validation to avoid someone manipulating the url and access to data they don't desserve.
Query string are ok, but don´t compromise security with them.
If the profile you are accessing is the current logged in user, there´s no need to send in the uid. Just go to /profile and load the current logged in user information.
if you are looking at other member profile, i recommend to just go with it´s 'username', an encrypted id or a Guid.
Exposing user ids to clients are generally not a good idea.

ASP.NET URL remapping &redirection - Best Practice needed

This is the scenario: I have a list of about 5000 URLs which have already been published to various customers. Now, all of these URLs' location has changed on my server side. The server is still the same though. This is a ASP.NET website with .NET3.5/C#.
My requirement is : Though the customers use the older source URL they should be redirected to the new URL without any perceived change or intermediate redirection message etc.
I am trying to make sense of the whole scenario:
Where would I put the actual mapping of Old URL to New URL -- in a database or some config. file or is there a better option?
How would I actual implement a redirect:
Should I write a method with Server.Transfer ot Response.Redirect?
And is there a best practice to it like - placing the actual re-routing in HTTPModules..or is it Application_BeginRequest?
I am looking to achieve with a best-practice compliant methodology and very low performance degradation, if any.
If your application already uses a database then I'd use that. Make the old URL the primary key and lookups should be very fast. I'd personally wrap the whole thing in .NET classes that abstracts it and allow you to create a Dictionary<string,string> of all the URLs which can be loaded into memory from the DB and cached. This will be even faster.
Definitely DON'T use Server.Transfer. Instead you should do a 301 Permanently Moved redirect. This will let search engines know to use the new URL. If you were using NET 4.0 you could use the HttpResponse.RedirectPermanent method. However, in earlier versions you have to set the headers yourself - but this is trivial.
Keep the data in a database, but load into ASP.NET cache to reduce access time.
You definitely want to use HTTPModules. It's the accepted practice, and having recently tried to do it inside Global.asax, I can tell you that unless you want to do only the simplest kind of stuff (i.e. "~/mypage.aspx/3" <-> "~/mypage.aspx?param1=3) it's much more complicated and buggy than it seems.
In fact, I regret even trying to roll my own URL rewriting solution. It's just not worth it if you want something you can depend on. Scott Guthrie has a very good blog post on the subject, and he recommends UrlRewriter.net or UrlRewriting.net as a couple of free, open-source URL rewriting solutions.
Good luck.

How does the URL Rewrite Module Work

I'm probably going to use the URL rewrite module for IIS 7 eventually and I have a fairly straight forward question that I really can't find the answer to.
If you have a base case of:
http://yoururl.com/page.aspx?ID=7
You can obviously have it rewritten to:
http://yoururl.com/page/7 or whatever you want.
My question is this: When using this module can you still use Request.Querystring["page"] on the rewritten querystring. How does the Request.URL stuff work. Does asp.net still provide the un-rewritten url or does it provide the rewritten one.
I would assume that your C#/asp.net code is completely unaffected by the url rewriting, as that's more or less the point, but I want to be crystal clear.
Secondary question: What is the best practice for how you should code a website when using the rewritten. Should you code links in the written style, or continue using querystrings?
When using this module can you still use Request.Querystring["page"] on the rewritten querystring.
Yes, you will be able to access the re-written QueryString in that way.
How does the Request.URL stuff work. Does asp.net still provide the un-rewritten url or does it provide the rewritten one.
Request.Url will be the re-written URL, but Request.RawUrl will be the original URL.
Should you code links in the written style, or continue using querystrings?
Yes, code your links in the way you want them to be seen by end users, and then in your code ensure you're aware of and document the changed format.
There is loads of information and tutorials on the IIS website here:
http://learn.iis.net/page.aspx/460/using-the-url-rewrite-module/

Why does IIS wild card mapping break my AJAX calls?

I'm trying to use jQuery to make some AJAX calls, but because I have wild card mapping (to .NET) in IIS 6 turned on, it doesn't seem to work. Disabling the mapping makes everything magically work.
I've put the web method attribute on methods in both an .aspx page and an .asmx web service, but neither work. Here is the sample URL that I am using for the AJAX calls:
localhost/UserChecker.aspx/CheckIfUserEmailsExists
localhost/UserChecker.asmx/CheckIfUserEmailsExists
I figure it must be something with the way .NET is interpreting the URL's but I'm not entirely sure why. More importantly, I'm not sure how to fix it, other than to disable wild card mapping! Is there any other way???
UPDATE
The CMS I am using (Kentico) does some URL routing, but even if I skip over the routing in the global.asax.cs code, I still get a 404.
Thanks in advance!
With the wildcard mapping on IIS will run the initial request via the wildcard handler first. This will be done BEFORE any URL rewriting (or URL routing) by your CMS.
I think that is why you are getting 404.
You can also try to disable "verify file exists" checkbox on the wildcard mapping to cater for the scenario when the actual URL will be later rewritten to something else.
This is not a complete answer but I hope it points you in the direction of a solution.
Have you tried accessing the url directly in a browser and using some well placed breakpoints to track down the problem?
If you're getting 404s it sounds like your rules for routing aren't working.
[I'll update this if you can give a little more info about the behaviour you're seeing]
UPDATE
I think what might be happening is this:
You're providing a seperate mapping for your files with extensions (in these cases .aspx and .asmx):
localhost/UserChecker.aspx/CheckIfUserEmailsExists
localhost/UserChecker.asmx/CheckIfUserEmailsExists
These mappings are being used when you turn the wild card mappings off, and the '/CheckIfUserEmailsExists' is handled used or ignored.
When you turn on the wildcard mappings your routing isn't informing your app how to 'route' correctly.
If you removed the extensions (with wildcard mappings turned on) does the following work?
localhost/UserChecker/CheckIfUserEmailsExists
Add the appropriate URLs to the exclusion list: Use the "Excluded URLs" setting in the Site Manager->Settings tab. (basic help documentation)
I suggest checking the URl outside of your CMS framework; Issue has to be with the URL routing. No tsure how it was working without the wild card mapping.
Questions to understand:
1.Did you have your CMS running when trying without wild card mapping?
2. How does this CMS system interact with IIS; IASPI dll ? or HTTP Handlers/modules?

Categories