Configuration Options to Secure ASP.NET Application

If you have ASP.NET website on internet, you must make sure to implement following cofiguration steps to secure your website. Block libwww-perl attack in ASP.NET Application hosted in IIS – Follow this article to configure this. Some response headers reveal technical details about the server which must be removed. For example a sample response from an ASP.Net application may look like this In this response “Server”, “X-AspNet-Version”, “X-Powered-By” headers are revealing technical details about the server. We can remove these unnecessary IIS response headers as following Remove “X-Powered-By” Header – Open web.config and check for customHeaders tag. If this is not already there, then add it as child of “<httpProtocol>” and add “remove” entry for X-Powered-By as shown below <configuration> <system.webServer> <httpProtocol> <customHeaders> <remove name=”X-Powered-By” /> </customHeaders> </httpProtocol> </system.webServer> </configuration> You should also check the response from your Asp.Net application if this is using a shared hosting which may add additional server specific information to response headers. Add remove entry[…]

Quick Tip

Send Email from GoDaddy Asp.Net Application

In my previous article we looked at how to use Google account and SMTP server to programatically send mail to an email address. We can use the same code with minor changes for GoDaddy application which is using shared hosting. We will develop a “Contact us” page here using SMTP server from GoDaddy. The first step is to create a web service using System; using System.Configuration; using System.Net.Mail; using System.Web.Services; namespace GoDaddy.Email { /// <summary> /// Summary description for Mail /// </summary> [WebService(Namespace = “http://tempuri.org/”)] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. [System.Web.Script.Services.ScriptService] public class Mail : System.Web.Services.WebService { [WebMethod] public string SendEmail(string email, string name, string body) { try { var toEmailAddress = ConfigurationManager.AppSettings[“ToEmailAddress”].ToString(); var smtpHost = ConfigurationManager.AppSettings[“SMTPHost”].ToString(); var smtpPort = ConfigurationManager.AppSettings[“SMTPPort”].ToString(); MailMessage mailMessage = new MailMessage(); mailMessage.To.Add(toEmailAddress); mailMessage.From = new MailAddress(email, name); mailMessage.Subject = “Contact[…]

Quick Tip

Send Email from Asp.Net Application using Google Account and SMTP

In order to send mail from the application we can use SMTP server from Google (which off course has certain limitations). We can use a Google mail account and send the mail using SMTP server from Google. This works very well for Asp.net applications which need to use a simple form such as “Contact Us”. An example of this is explained below. We will use AJAX to send the request to an ASP.Net web service which sends the mail from the server side. Create a web service as following using System; using System.Configuration; using System.Net.Mail; using System.Web.Services; namespace GoDaddy.Email { /// <summary> /// Summary description for Mail /// </summary> [WebService(Namespace = “http://tempuri.org/”)] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. [System.Web.Script.Services.ScriptService] public class Mail : System.Web.Services.WebService { [WebMethod] public string SendEmail(string to, string subject, string body)[…]

Quick Tip

Different MasterPage for Mobile and Desktop in ASP.NET

Now a days more people have been accessing the web on mobile devices as compared to desktops and creating mobile versions of websites have become a necessity. In ASP.NET Web Forms application we can switch between different mastre pages basis which device user is using to access the site. This gives a lot of advantages such as changing layout of the pages, applying different style sheets and even load different content if the need be. To achieve this im ASP.NET Web Forms application simply define a base page as following public partial class BasePage : System.Web.UI.Page { protected void Page_PreInit(Object sender, EventArgs e) { if (Request.Browser.IsMobileDevice) { this.MasterPageFile = “~/Mobile.master”; } else { this.MasterPageFile = “~/Desktop.master”; } } } Now rest of the pages (such as example below) can simply inherit base page and all those pages will have different master pages for mobile and desktop. public partial class MyPage :[…]

Quick Tip

Bundling and Minification in ASP.NET Web Forms Application

ASP.NET has in-built for bundling of multiple resources such as js or css files into one file and then minifiy the files to reduce the number of calls made to the server and total data size downloaded from the server thus reducing the total download time and enhanding application’s performance.  In order to use this in web forms application which target version .NET 4.5 and higher, following steps are required 1. Go to NuGet Package Manager and install Microsoft.AspNet.Web.Optimization and Microsoft.AspNet.Web.Optimization.WebForms packages 2. Check web.config to make sure “webopt” tag prefix is added (once you install Microsoft.AspNet.Web.Optimization.WebForms) <pages> <namespaces> <add namespace=”System.Web.Optimization” /> </namespaces> <controls> <add assembly=”Microsoft.AspNet.Web.Optimization.WebForms” namespace=”Microsoft.AspNet.Web.Optimization.WebForms” tagPrefix=”webopt” /> </controls> </pages> 3. Add a class file as following and define the resources you want to bundle public class BundleConfig { public static void RegisterBundles(BundleCollection bundles) { Bundle cs = new Bundle(“~/bundles/cssv1”, new CssMinify()); cs.Include(“~/Resources/css/bootstrap.min.css”, “~/Resources/css/app.css”); bundles.Add(cs); bundles.Add(new ScriptBundle(“~/bundles/jsv1”).Include( “~/Resources/js/jquery.min.js”, “~/Resources/js/bootstrap.min.js”)); BundleTable.EnableOptimizations = true;[…]

Quick Tip

Block libwww-perl attack in ASP.NET Application hosted in IIS

Libwww-perl (LWP) is a WWW client/server library for perl which can be used by hackers, spammers or automated bots to attack a website to steal information so we need to apply security to our web application to eliminate many simpler attacks on the website. In order to fix this issue in an ASP.NET web application we can use the following code. Add the code in Application_BeginRequest method of Global.asax file in your web application protected void Application_BeginRequest(object sender, EventArgs e) { string userAgent = HttpContext.Current.Request.ServerVariables[“HTTP_USER_AGENT”]; if (!string.IsNullOrEmpty(userAgent)) { if (“Libwww-perl”.ToLower().Equals(userAgent.ToLower())) { Send403(Response); } } } internal void Send403(HttpResponse response) { SendResponse(response, 0x193, “403 FORBIDDEN”); } internal void SendResponse(HttpResponse response, int code, string strBody) { HttpContext current = HttpContext.Current; object obj2 = current.Items[“ResponseEnded”]; if ((obj2 == null) || !((bool)obj2)) { current.Items[“ResponseEnded”] = true; response.StatusCode = code; response.Clear(); if (strBody != null) { response.Write(strBody); } response.End(); } } Another option is to disallow Libwww-perl user[…]

SEO Tip: Set Preferred URL in ASP.NET Application

Search engines treat website URL with and without “www” differently. Though both URLs point to the same destination, it’s important to pick one and set as your preferred URL so that search engines don’t two URLs as duplicate content. Websites use 301 redirect for this. The example code to redirect non-www URL to www URL in an ASP.NET application would be as following. Add following code snippet in Application_BeginRequest method of your Global.asax. Replace URL (somewebsite.com) with your website URL in the code and you are all set. protected void Application_BeginRequest(object sender, EventArgs e) { if (HttpContext.Current.Request.Url.AbsoluteUri.ToLower().StartsWith(“http://somewebsite.com”)) { string newUrl = HttpContext.Current.Request.Url.AbsoluteUri.ToLower().Replace(“http://somewebsite.com”, “http://www.somewebsite.com”); Response.Status = “301 Moved Permanently”; Response.AddHeader(“Location”, newUrl); } } If you want to do the opposite and direct www URL to non-www URL simply change the code as following protected void Application_BeginRequest(object sender, EventArgs e) { if (HttpContext.Current.Request.Url.AbsoluteUri.ToLower().StartsWith(“http://www.somewebsite.com”)) { string newUrl = HttpContext.Current.Request.Url.AbsoluteUri.ToLower().Replace(“http://www.somewebsite.com”, “http://somewebsite.com”); Response.Status = “301 Moved Permanently”;[…]

Add SEO Friendly URL’s to ASP.NET Application

It’s very important for a web site to create SEO friendly URL’s and remove page extensions such as .aspx. When search engines look at a site, the first thing they analyze is the page URL which help them ascertain what the page content is about. In ASP.NET application Routes can be used for this which are URL patterns used for processing requests and can be used to construct URLs dynamically. The Global.asax file is a special file that contains event handlers for ASP.NET application lifecycle events. The route table is created during the Application Start event in Global.asax. In order to do so add Global Application Class (Global.asax) to your ASP.NET Web Application if it is not created yet. The following example shows how to add a route. protected void Application_Start(object sender, EventArgs e) { try { RegisterRoutes(RouteTable.Routes); } catch (Exception ex) { // Log Exception here } } protected static void RegisterRoutes(RouteCollection routes) { if[…]