Wednesday 11 December 2013

Exception Handling in ASP.NET MVC 4

    What does the user see when a runtime error occurs in an ASP.NET web application? The answer depends on how the website's <customErrors> configuration. By default, users are shown an unsightly yellow screen proclaiming that a runtime error has occurred. This tutorial shows how to customize settings to handle runtime exceptions.

We will use two attributes to handle error in an MVC application
  • customErrors attribute defined in web.config
  • HandleError attribute comes with default MVC Application
  1. Set custom errors mode to ON in web config.
    • From custom error we can set that where we can redirect a user when some exception occurs in our application.
    • Set defaultRedirect attribute'value & add a sub tag for 404 error. Values for defaultRediret and redirect are the URLs of the pages for default redirection when some error occurs.

      <!-- Custom Error Handling -->
      <customErrors mode="On" defaultRedirect="~/Home/DefaultError">
      <error statusCode="404" redirect="~/Home/Error404" />
      </customErrors>



  2. Use HandleError filter attribute

    • The HandleError filter works only if the <customErrors> section is turned on in web.config.
    • HandleError attribute provided by MVC framework.
    • It handle only status code 500 errors. It does not handle 404 not found or other types of errors.
    • If you use both customError attribute in web.config & HandleError attribute and any internal server error (500) occurs then HandleError will override behaviour of customError attribute & will handle error with it's own way.
    Example of Controller level handling
[HandleError]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";

        return View();
    }

    public ActionResult About()
    {
        return View();
    }
}

  1. You can use HandleError attribute at
    • Action Level – by adding this attribute on Action ex. [HandleError]
    • Controller Level - by adding this attribute on Controller ex. [HandleError]
    • Application Level - by registering filter in FilterConfig.cs in App_Start folder
Example of Application level handling
     public class FilterConfig
   {
     public static void RegisterGlobalFilters(GlobalFilterCollection filters)
     {
     filters.Add(new HandleErrorAttribute());
     }
    }
  1. When error occurs, this will redirect to a view which is in shared folder named 'Error'
  2. You can change view name. ex. [HandleError(View = "DatabaseError")]
  3. That's all
  4. Redirection sequence of error handling
    • For ( 500 Internal server error)
      1. Redirect to view of Handle Error Attribute
      2. Redirect to Url defaultRedirect defined in customErrors tag in web.config. ( if Handle Error is not registered at any level)
    • For ( 404 or other types of errors)
      1. Other url according to status code defined in customErrors tag.

Note:
  1. Handle Error is an inbuilt Filter. We can use our own custom filter attribute by making a class which is derived from Filter Attribute & implements Iexception Filter interface.
  2. To handle ajax request's exception. Visit the link given below.
  3. For more detail about exception. Visit this link :

Sunday 8 December 2013

How to implement Simple Membership in MVC 4

Importanat Note: We can initialize simple Membership in MVC 4 by two ways. 

 1.   By InitializeSimpleMembershipAttribute which is already present on Account Controller.
 2.   FromGlobal.asax.

Here we are implementing it with second way. 

So First of all remove InitializeSimpleMembershipAttribute  from Account Controller and follow these steps.


 1. Copy this function in Global.asax 

  void initializeMembership()
        {
            if (!WebSecurity.Initialized)
                WebSecurity.InitializeDatabaseConnection("ConnectionString""UserProfile""UserId""UserName", autoCreateTables: true);

        }


2. This function checks the database of given ConnectionString. Create Membership Table if they are not present, and initializes Simple Membership.

3.    Call this function in the end of Application_Start event. Like given below.

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            initializeMembership();

        }

      
 
4. Tables for membership have now been created in DataBase of given Connection string.

5.  You can also add more fields in UserProfile Table. (Not mentioning here now)

6.  Now add default login url in system.web node in web config if not present.
      
              <authentication mode="Forms">
                     <forms loginUrl="~/Account/Login" timeout="2880" />
              </authentication>


7.   Also add some other settings in system.web in web config. This setting enables SimpleMembershipProvider  explicitly.
      
    <!--MVC 4 Simple Membership Settings-->
              <roleManager enabled="true" defaultProvider="SimpleRoleProvider">
                     <providers>
                           <clear/>
                           <add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData"/>
                     </providers>
              </roleManager>
              <membership defaultProvider="SimpleMembershipProvider">
                     <providers>
                           <clear/>
                           <add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
                     </providers>
              </membership>
             
    <!--End of MVC 4 Simple Membership Settings-->