Windows 2012 Hosting - MVC 6 and SQL 2014 BLOG

Tutorial and Articles about Windows Hosting, SQL Hosting, MVC Hosting, and Silverlight Hosting

ASP.NET Hosting - ASPHostPortal.com :: SEO Tips For ASP.NET URL’s

clock March 14, 2016 20:37 by author Armend

If you are building a new ASP.NET application, SEO has become a big factor in how you plan the structure / code of the site.  But quite an important part of the site which are often overlooked are the URL’s, and a lot of people do the basics which I’ll show below but there are a few common things people tend to miss or never thought could be a problem. I use ISAPI rewrite for most of my sites, which is an amazingly effective tool for sorting duplicate content and SEO issues which I’ll show below

 

  • Rewrite your URL’s to be useful / descriptive and stick away from using the old dynamic way

i.e. mypage.aspx?e=54&b=99
Google even tell you this is not ideal in the webmaster guidelines (See bottom of Design & Content Guidelines section) - http://www.google.co.uk/support/webmasters/bin/answer.py?answer=35769&hlrm=en_uk More...



ASP.NET MVC - ASPHostPortal.com :: 7 Tips for Developing a Secure ASP.NET Web Application

clock March 7, 2016 20:07 by author Armend

As the usage of the internet and the number of web applications over the internet have gone exponentially high there are bad people who continuously work around the clock to hack them. It may be for personal gain or just as an amateur act. Despite the intention of the bad guy the damage caused to the organization hosting the site or its users should be taken into account. As a professional web application developer it is a must to be aware of the best practices to follow in order to make the application more secure. In this article I will be listing and explaining my top 7 tips for developing a secure asp.net application.

Don’t Let Your Users be Victims of Click Jacking

Have you ever thought about someone framing your website onto theirs, making your users to be the victims of click jacking? Yes, the attackers can load your website onto their site in an iframe. They can then skillfully place their transparent controls over your website and fetch the PII information, user credentials, make them perform an unwanted task like exposing their financial information, etc.
In order to prevent that you will have to use a frame busting technique. The following script will not allow your website to be iframed. This can be placed in your master pages.

<script type="text/javascript" language="javascript">
        //Check if the top location is same as the current location
        if (top.location.hostname != self.location.hostname) {
            //If not then set the top to you current
            top.location.href = self.location.href;
        }
    </script>

In addition to the above script don’t forget to add the following header, which informs the browser to DENY framing of this website. This is supported in all major browsers except IE versions less than 8.
The header should be added in the global.asax application start event.  

protected void Application_Start(object sender, EventArgs e)
    {
                HttpContext.Current.Response.AddHeader("x-frame-options", "DENY");
    }    

White List the Request URL

Though we have many techniques to perform the security preventions inside the application it is most important to prevent the bad data from being entered into your website at the first place. Most attacks happen through the query string values passed through the URL. It is a best security practice to define a common place like an HttpModule to white list the URL, i.e. sanitize the entire URL with a set of white listed characters and drop all the bad ones. It means you will not encourage any other characters apart from a white listed set defined in your application.
It is important for you to know that black listing is not a foolproof mechanism and it can be broken by the hackers easily.

Practice of Encoding the Data

While processing and sending, the data in the response that is fetched from outside the trust boundary should always be encoded. The type of encoding may differ based on the usage of the non-trusted data. For example perform an HtmlEncode for the data that is sent to the client page.

Label1.Text = Server.HtmlEncode(Request.QueryString["BadValue"]);

Encoding the data will make the XSS scripts inactive and prevent them from being executed. Microsoft has provided the AntiXss library, which provides more sophisticated encoding methods including the JavascriptEncode.
Using Cookies
As a web developer you should take utmost care while using cookies, which may open a back door for the hackers to get into your applications. Following are the best practices while using a cookie to store information.

1. Is your website is hosted under SSL? Then be sure to mark your cookies as secure. This will make them available only in the SSL transmissions.

             HttpCookie cookie = new HttpCookie("MySecureCookie");
        cookie.Value = "This is a PII information";
        cookie.Secure = true;

2. If your website is not SSL enabled then always encrypt the values using a strong encryption mechanism like AES 256 and then store them in the cookies.

Secure the Service Calls (WCF / Web Service)

Are you exposing WCF services through basicHttpBinding? Then think again because the messages transmitted over will be plain text and any intruder will be able to trap the requests and even simulate them easily. Use wsHttpBinding, which will transport the messages in an encrypted format, which makes the life of the intruder hard.
Though you make lots of protections for your WCF or web services it is a best practice to host the services under an SSL layer.

Never Deploy the Application with debug=”true”

It is strongly recommended not to deploy your applications in the production environment with compilation debug=”true” in your web.config. This will result in a big nightmare for performance and security of the application.
This may leak too much information for the attackers, for example the stack trace in the event of an unhandled exception and the debug trace information. Such exposure of the internals will be good bucks for the attackers.

<system.web>
        <compilation debug="false" targetFramework="4.0" />
    </system.web>

Thinking About Turning Off ViewStateMAC?

Turning off ViewStateMAC will create a security loophole in your asp.net application if you are using Viewstate on your web pages. The intruders will easily be able to intercept, read the 64 bit encoded values and modify them to do some bad things to your website. Having it turned on ensures that the viewstate values are not only encoded but also a cryptographic hash is performed using a secret key.

<pages enableViewStateMac="true"></pages>

I hope this article is useful for the developers who thrive at making their asp.net application an absolutely impossible place for the hackers to deal with.
Happy reading!



ASP.NET MVC - ASPHostPortal.com :: Simple Tips for ASP.NET MVC Model Binding

clock March 1, 2016 18:25 by author Armend

Tips for ASP.NET MVC Model Binding

Model binding in the ASP.NET MVC framework is simple. Your action methods need data, and the incoming HTTP request carries the data you need. The catch is that the data is embedded into POST-ed form values, and possibly the URL itself. Enter the DefaultModelBinder, which can magically convert form values and route data into objects. Model binders allow your controller code to remain cleanly separated from the dirtiness of interrogating the request and its associated environment.    
Here are some tips on how to take advantage of model binding in your MVC projects.

 

Tip #1: Prefer Binding Over Request.Form

If you are writing your actions like this ..

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create()

{
    Recipe recipe = new Recipe();
    recipe.Name = Request.Form["Name"];  
    // ...  
    return View();
}

Then you are doing it all wrong. The model binder can save you from using the Request and HttpContext properties – those properties make the action harder to read and harder to test. One step up would be to use a FormCollection parameter instead:
public ActionResult Create(FormCollection values)

{
    Recipe recipe = new Recipe();
    recipe.Name = values["Name"];               
    // ...        
    return View();
}

With the FormCollection you don’t have to dig into the Request object, and sometimes you need this low level of control. But, if all of your data is in Request.Form, route data, or the URL query string, then you can let model binding work its magic:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Recipe newRecipe)
{           
    // ...  
    return View();
}

In this example, the model binder will create your newRecipe object and populate it with data it finds in the request (by matching up data with the recipe’s property names). It’s pure auto-magic. There are many ways to customize the binding process with “white lists”, “black lists”, prefixes, and marker interfaces. For more control over when the binding takes place you can use the  UpdateModel and TryUpdateModel methods. Just beware of unintentional binding – see Justin Etheredge’s Think Before You Bind.

Tip #2: Custom model binders

Model binding is also one of the extensibility points in the MVC framework. If you can’t use the default binding behavior you can provide your own model binders, and mix and match binders. To implement a custom model binder you need to implement the IModelBinder interface. There is only method involved - how hard can it be?
public interface IModelBinder

{
    object BindModel(ControllerContext controllerContext,
                     ModelBindingContext bindingContext);
}

Once you get neck deep into model binding, however, you’ll discover that the simple IModelBinder interface doesn’t fully describe all the implicit contracts and side-effects inside the framework.  If you take a step back and look at the bigger picture you’ll see that model binding is but one move in a carefully orchestrated dance between the model binder, the ModelState, and the HtmlHelpers. You can pick up on some of these implicit behaviors by reading the unit tests for the default model binder.

If the default model binder has problems putting data into your object, it will place the error messages and the erroneous data value into ModelState. You can check ModelState.IsValid to see if binding problems are present, and use ModelState.AddModelError to inject your own error messages. See this very simple tutorial for more information on how ModelState and HtmlHelpers can work together to present validation errors to the user. 
If you scroll down the comments to post you’ll see code. If a conversion fails, the code will use ModelState.AddModelError to propagate the error. Both the controller action and the view can look in ModelState to see if there was a binding problem. The controller would need to check ModelState for errors before saving stuff into the database, while the view can check ModelState for errors to give the user validation feedback. One important note is that the HtmlHelpers you use in a view will require ModelState to hold both a value (via ModelState.SetModelValue) and the error (via AddModelError) or you’ll have runtime errors (null reference exceptions). The following code can demonstrate the problem:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection Form)
{
    // this is the wrong approach ...
    if (Form["Name"].Trim().Length == 0)
        ModelState.AddModelError("Name", "Name is required");
    return View();
}

The above code creates a model error without ever setting a model value. It has other problems, too, but it will create exceptions if you render the following view.

<%= Html.TextBox("Name", Model.Name) %>

Even though you’ve specified Model.Name as the value for the textbox, the textbox helper will see the model error and attempt to display the “attempted value” that the user tried to put in the model. If you didn’t set the model value in model state you’ll see a null reference exception.

Tip #3: Custom Model Binding via Inheritance

If you’ve decided to implement a custom model binder, you might be able to cut down on the amount of work required by inheriting from DefaultModelBinder and adding some custom logic. In fact, this should be your default plan until you are certain you can’t subclass the default binder to achieve the functionality you need. For example, suppose you just want to have some control over the creation of your model object. The DefaultModelBinder will create object’s using Activator.CreateInstance and the model’s default constructor. If you don’t have a default constructor for your model, you can subclass the DefaultModelBinder and override the CreateModel method.
Jimmy Bogard has an example of sub classing the DefaultModelBinder in his post titled “A Better Model Binder”.

Tip #4: Using Data Annotations for Validation

Brad Wilson explains everything beautifully in this post: DataAnnotations and ASP.NET MVC.
I encourage you to go read Brad’s post, but if you are in a hurry, here is a summary:

.NET 3.5 SP1 shipped a System.ComponentModel.DataAnnotations assembly that looks to play a central role as we move forward with the .NET framework. By using data annotations and the DataAnnotationsModelBinder, you can take care of most of your server-side validation by simply decorating your model with attributes.

public class Recipe
{
    [Required(ErrorMessage="We need a name for this dish.")]
    [RegularExpression("^Bacon")]
    public string Name { get; set; }

    // ...
}

The DataAnnotationsModelBinder is also a great sample to read and understand how to effectively subclass the default model binder.

Tip #5 : Recognize Binding and Validation As Two Phases

Binding is about taking data from the environment and shoving it into the model, while validation is checking the model to make sure it meets our expectations. These are different different operations, but model binding tends to blur the distinction. If you want to perform validation and binding together in a model binder, you can – it’s exactly what the DataAnnotationsModelBinder will do. You can also find samples like Automatic Model Validation with ASP.NET MVC, xVal, Castle, and a Custom Binder (John McDowall), and Enterprise Library Validation Application Block with MVC Binders (Steve Michelotti).  However, one thing that is often overlooked is how the DefaultModelBinder itself separates the binding and validation phases. If all you need is simple property validation, then all you need to do is override the OnPropertyValidating method of the DefaultModelBinder.

Tip #6: Binders Are About The Environment

Earlier I said that “model binders allow your controller code to remain cleanly separated from the dirtiness of interrogating the request and its associated environment”. Generally, when we think of binder we think of moving data from the routing data and posted form values into the model. However, there is no restriction of where you find data for your model. The context of a web request is rich with information about the client. A good example is another Scott Hanselman post on automatically binding the user’s identity into a model see: IPrincipal (User) ModelBinder in ASP.NET MVC for easier testing.

In Conclusion

Model binding is beautiful magic, so take advantage of the built-in magic when you can. I think the topic of model binding could use it’s own dedicated web site. It would be a very boring web site with lots of boring code, but model binding has many subtleties. For instance, we never even got to the topic of culture in this post.
Do you have any model binding tips?



About ASPHostPortal.com

We’re a company that works differently to most. Value is what we output and help our customers achieve, not how much money we put in the bank. It’s not because we are altruistic. It’s based on an even simpler principle. "Do good things, and good things will come to you".

Success for us is something that is continually experienced, not something that is reached. For us it is all about the experience – more than the journey. Life is a continual experience. We see the Internet as being an incredible amplifier to the experience of life for all of us. It can help humanity come together to explode in knowledge exploration and discussion. It is continual enlightenment of new ideas, experiences, and passions


Author Link


Corporate Address (Location)

ASPHostPortal
170 W 56th Street, Suite 121
New York, NY 10019
United States

Sign in