asp net mvc
Dynamic Robots.txt in ASP MVC
0I recently had the need to switch a robots.txt file dynamically, depending on whether a site was deployed to live or beta servers. The solution was very simple, ditch the real file and replace it with a controller action. This is a brief note on how I did this. I don’t pretend this is an ideal solution, it was something I knocked together before I went out for dinner.
The solution I went for was in three parts: a web.config transform, routing and the controller itself.
The web config transform for my live site looks like this:
<?xml version="1.0"?><configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform"> <appSettings> <add key="SiteStatus" value="live" xdt:Transform="SetAttributes" xdt:Locator="Match(key)"/> </appSettings></configuration>The route is equally simple:
routes.MapRoute( "Robots.txt", "Robots.txt", new { controller = "Robots", action = "RobotsText" });
And finally the actual controller:
public class RobotsController : Controller{ public FileContentResult RobotsText() { var content = "User-agent: *" + Environment.NewLine;
if (string.Equals(ConfigurationManager.AppSettings["SiteStatus"], "live", StringComparison.InvariantCultureIgnoreCase)) { content += "Disallow: /elmah.axd" + Environment.NewLine; content += "Sitemap: http://www.jacquelinewhite.co.uk/sitemap.xml"; } else { content += "Disallow: /" + Environment.NewLine; }
return File( Encoding.UTF8.GetBytes(content), "text/plain"); }}And there we have it, my robots.txt file now is customised on a per deployment basis.
Handling Google Instant in ASP MVC
0I love google chrome, it’s how browsers should be, it just works. The one thing I really like about it is the instant setting. The problem is that most sites don’t really know the difference between a bad url and a url that is being typed.
Well, now you can and it’s really simple.
The following extension method will let your controller know if it’s a full request or simply a user busy typing:
public static class RequestExtensions{ public static bool IsPreview(this HttpRequestBase request) { var purpose = request.Headers["X-Purpose"] ?? string.Empty; return string.Equals(": preview", purpose, StringComparison.InvariantCultureIgnoreCase); }}A very simple use of it would be something like this:
public virtual ActionResult Error404(){ Response.StatusCode = (int)HttpStatusCode.NotFound; if (Request.IsPreview()) { ViewBag.Message = "Nope, I've haven't go that, keep typing."; } else { ViewBag.Message = "Sorry, but the file you requested was not found on the server."; }
return View();}Let me know if you use this is a more creative way.