European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

Europe ASP.NET/MVC Hosting :: Creating ASP.NET WebApplication/ASP.NET MVC Application Membership Database on SQL Server Rather Than LocalDb

clock January 21, 2013 03:43 by author Scott

How can a DB be created in SQL Server rather than locally (LocalDb) which is the default?

When you create a new ASP.NET MVC Application (using regular template "Internet") or ASP.NET WebApplication, you will notice the following connection string in the Web.config file:

<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-MvcApplication1-20121005163323;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-
 MvcApplication1-20121005163323.mdf" providerName="System.Data.SqlClient" />


Actually this helps the MVC Application or ASP.NET WebApplication to generate a database locally (within the project's App_Data folder) at run-time for accounts and login management (membership). If however you want to generate this database in SQL Server then you can make some quick changes in the above Web.config file to do that, so here is what you need replace in the above db mapping.

<add name="DefaultConnection" connectionString="Data Source=ITORIAN-PC;Initial Catalog=ASPNETMembership;Integrated Security=True;MultipleActiveResultSets=True;" providerName="System.Data.SqlClient" />

You probably have a different data source so change it before running. Now, run the application and click on the "Register" link to create an account and then you are all done.

Open the SQL Server Management Studio and look at the generated DB for this application.

 



European ASP.NET 4.5 Hosting - Amsterdam :: How to Create ASP.NET Permanent User Login

clock October 16, 2012 08:48 by author Scott

Introduction

This article describes how to create a permanent user login session in ASP.NET. The sample code includes an ASP.NET MVC4 project to control the user registration and login process. But you can use this technique in any type of ASP.NET project.

Forms Authentication


Before getting into the depth of this article, you must be familiar with forms authentication in ASP.NET. The configuration of form authentication resides in web.config file which has the following configuration-file fragment with the assigned values.


<authentication mode="Forms">
      <forms loginUrl="~/Account/LogOn"
             protection="All"
             timeout="1"
             name=".USERLOGINCONTROLAUTH"
             path="/"
             requireSSL="false"
             slidingExpiration="true"
             defaultUrl="~/Home/Index"
             cookieless="UseDeviceProfile"
             enableCrossAppRedirects="false"/></authentication>

The default values are described below:

-
loginUrl points to your application's custom logon page. You should place the logon page in a folder that requires Secure Sockets Layer (SSL). This helps ensure the integrity of the credentials when they are passed from the browser to the Web server.

-
protection is set to All to specify privacy and integrity for the forms authentication ticket. This causes the authentication ticket to be encrypted using the algorithm specified on the machineKey element, and to be signed using the hashing algorithm that is also specified on the machineKey element.

-
timeout is used to specify a limited lifetime for the forms authentication session. The default value is 30 minutes. If a persistent forms authentication cookie is issued, the timeout attribute is also used to set the lifetime of the persistent cookie.

-
name and path are set to the values defined in the application's configuration file.

-
requireSSL is set to false. This configuration means that authentication cookies can be transmitted over channels that are not SSL-encrypted. If you are concerned about session hijacking, you should consider setting requireSSL to true.

-
slidingExpiration is set to true to enforce a sliding session lifetime. This means that the session timeout is periodically reset as long as a user stays active on the site.

-
defaultUrl is set to the Default.aspx page for the application.

-
cookieless is set to UseDeviceProfile to specify that the application use cookies for all browsers that support cookies. If a browser that does not support cookies accesses the site, then forms authentication packages the authentication ticket on the URL.

-
enableCrossAppRedirects is set to false to indicate that forms authentication does not support automatic processing of tickets that are passed between applications on the query string or as part of a form POST.

FormsAuthentication.SetAuthCookie Method

This method creates an authentication ticket for the supplied user name and adds it to the cookies collection of the response, or to the URL if you are using cookieless authentication. The first overload of this function has two parameters:


-
userName: The name of the authenticated user

-
createPersisntentCookie: True to create a persistent cookie (one that is saved across browser sessions); otherwise, false.

This method add a cookie or persistent cookie to the browser with an expire time set in "timeOut" parameter with the name and path set in "name" and "path" parameter. The user will be automatically logged out once the cookie is expired. So the user login session depends on the expire of forms authentication ticket saved in browser cookie. Here, I will create a permanent user login session using this technique.

Cookie Helper

The functionality of this class is to add a form authentication ticket to the browser cookie collection with a life time expiry.


public sealed class CookieHelper
{
    private HttpRequestBase _request;
    private HttpResponseBase _response;

    public CookieHelper(HttpRequestBase request,
      HttpResponseBase response)
      {
            _request = request;
            _response = response;
      }

    //[DebuggerStepThrough()]
    public void SetLoginCookie(string userName,string password,bool isPermanentCookie)
    {
        if (_response != null)
        {
            if (isPermanentCookie)
            {
                FormsAuthenticationTicket userAuthTicket =
                  new FormsAuthenticationTicket(1, userName, DateTime.Now,
                  DateTime.MaxValue, true, password, FormsAuthentication.FormsCookiePath);
                string encUserAuthTicket = FormsAuthentication.Encrypt(userAuthTicket);
                HttpCookie userAuthCookie = new HttpCookie
                  (FormsAuthentication.FormsCookieName, encUserAuthTicket);
                if (userAuthTicket.IsPersistent) userAuthCookie.Expires =
                                    userAuthTicket.Expiration;
                userAuthCookie.Path = FormsAuthentication.FormsCookiePath;
                _response.Cookies.Add(userAuthCookie);
            }
            else
            {
                FormsAuthentication.SetAuthCookie(userName, isPermanentCookie);
            }
        }
    }
}

This function is used in login page or control on the click of login button. In the attached sample project, the following function is written in AccountController class. This function validates the login of the user and then add a permanent form authentication ticket to the browser.

private bool Login(string userName, string password,bool rememberMe)
{
    if (Membership.ValidateUser(userName, password))
    {
        CookieHelper newCookieHelper =
            new CookieHelper(HttpContext.Request,HttpContext.Response);
        newCookieHelper.SetLoginCookie(userName, password, rememberMe);
        return true;
    }
    else
    {
        return false;
    }
}

 



European ASP.NET 4 Hosting - Amsterdam :: How to Fix ValidateRequest="false" in ASP.NET 4

clock September 27, 2012 06:03 by author Scott

If you are someone like me who have recently upgrade to ASP.NET 4.0, you may have come across Yellow Screen of Death with Http Request Validation Exception, something like:

“A potentially dangerous Request.Form value was detected from the client”

Exception Details
: System.Web.HttpRequestValidationException: A potentially dangerous Request.Form value was detected from the client

Surprisingly, you will still see this exception even if you have set ValidateRequest to false in either the Page Tag or Web.Config.


ValidateRequest="false" or  <pages validateRequest="false" />


This may end you being freak out identifying the problem.


The solution is perhaps very simple. I would recommend to go and read
ASP.NET 4 Breaking Changes.

“In ASP.NET 4, by default, request validation is enabled for all requests, because it is enabled before the BeginRequest phase of an HTTP request. As a result, request validation applies to requests for all ASP.NET resources, not just .aspx page requests. This includes requests such as Web service calls and custom HTTP handlers. Request validation is also active when custom HTTP modules are reading the contents of an HTTP request.and therefore request validation errors might now occur for requests that previously did not trigger errors.”


In order to revert to the behavior we had previously, you need to add the following setting in Web.config file:


<httpRuntime requestValidationMode="2.0"/>


And this should work!


Hope this helps!

 



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in