MVC extension Filter, which encrypts the login password by inheriting ActionFilterAttribute

Source: Internet
Author: User


There are 2 interfaces associated with Actionfilter:

-iactionfilter action execution before and after processing

void OnActionExecuting (ActionExecutingContext filtercontext);
You can process the request here, or even open a new request.

void onactionexecuted (Actonexecutedcontext filtercontext);
You can process the returned results here, or even cancel the return result.

About parameters ActionExecutingContext and Actonexecutedcontext are common:
are inherited from ControllerContext.
There are Actiondescriptor properties: Provides the details of the action
Has the ActionResult property: cancels the entire request when set to NULL

About Actonexecutedcontext Exclusive:
Canceled property: type bool, whether ActionExecutedContext is canceled by another action filter
Exception property: Exception thrown by action filter and action
exceptionhandled property: Type bool, whether the exception is handled

-iresultfilter the action returns the result before and after processing

Methods and properties are similar to Iactionfilter.
void onresultexecuted (ResultExecutedContext filtercontext);
void Onresultexecuting (ResultExecutingContext filtercontext);

Example: Inherit actionfilterattribute to encrypt login password

ActionFilterAttribute contains the following 4 methods:
void OnActionExecuting (ActionExecutingContext filtercontext);
void onactionexecuted (Actonexecutedcontext filtercontext);
void onresultexecuted (ResultExecutedContext filtercontext);
void Onresultexecuting (ResultExecutingContext filtercontext);
So, we can override these 4 methods in a derived class.

-Ideas

→ Encrypt the password before executing the action
→ After the action is executed, depending on whether the login succeeds, the return success or re-login view is determined.
→ Append some content after action returns the result

-Inherit ActionFilterAttribute

using System;
using System.Security.Cryptography;
using System.Text;
using SYSTEM.WEB.MVC;
using System.Web.Security;
namespace Mvcapplication1.extension
{
     Public class Encryptloginattribute:actionfilterattribute
    {
        Private string username;
        Private string password;
        Private BOOL false;
        Private string longdate;
        Private string lasttry;
         Public Override void OnActionExecuting (ActionExecutingContext filtercontext)
        {
            Username = filtercontext.httpcontext.request.form["username"];
            Password = filtercontext.httpcontext.request.form["password"];
            MD5 Md5hash = MD5. Create ();
            string Md5password = Getmd5hash (md5hash, password);
            bool result = Membership.ValidateUser (username, md5password);
            if (Result)
            {
                false);
                true;
                Longdate = DateTime.Now.ToLongDateString ();
            }
            Else
            {
                false;
                "-" + DateTime.Now.ToShortTimeString ();
            }
        }
         Public Override void onactionexecuted (ActionExecutedContext filtercontext)
        {
            if (isauthorized)
            {
                New "Welcome"};
            }
            Else
            {
                New ViewResult ();
                "Index";
                "Login fail";
                Filtercontext.result = Result;
            }
        }
         Public Override void onresultexecuted (ResultExecutedContext filtercontext)
        {
            if null &&!filtercontext.canceled)
            {
                ViewResult result = (ViewResult) Filtercontext.result;
                if null)
                {
                    if "Welcome")
                    {
                        FilterContext.HttpContext.Response.Write ("<p style= ' Color:green; ><br/>today is "
"<br/></p>");
                    }
                    Else if "Index")
                    {
                        FilterContext.HttpContext.Response.Write ("<p style= ' color:red; ><BR/>last Login attemp at "+lasttry+" <br/></p> ");
                    }
                    Filtercontext.result = Result;
                }
            }
        }
        Private Static string string Input)
        {
            String→byte[]
            byte [] data = Md5hash.computehash (Encoding.UTF8.GetBytes (input));
            New StringBuilder ();
            foreach (byte in data)
            {
                Stringbuilder.append (b.tostring ("X2"));
            }
            return stringbuilder.tostring ();
        }
    }
}

-homecontroller

using SYSTEM.WEB.MVC;
using System.Web.Security;
using Mvcapplication1.extension;
namespace Mvcapplication1.controllers
{
     Public class Homecontroller:controller
    {
         Public ActionResult Index ()
        {
            return View ();
        }
        [HttpPost]
        [Encryptlogin]
         Public ActionResult Login (stringstring password)
        {
            TODO: Save to database
            return null;
        }
         Public ActionResult SignOut ()
        {
            FormsAuthentication.SignOut ();
            return Redirecttoaction ("Index");
        }
    }
}

-home/index.cshtml for login page

@{
    "Index";
    "~/views/shared/_layout.cshtml";
}
<p style="color:red;" > @ViewBag .message</p>
@using (Html.BeginForm ("Login""Home"new"LoginForm"})
{
    <p>
        User name: @Html. TextBox ("username"nullnew"width:100px"})
    </p>
    <p>
        Password: @Html. Password ("Password"nullnew"width:100px"})
    </p>
    <p>
        <input type="Submit" name="login"Value="Login"/>
    </p>
}

-web.config Related Configurations

<authentication mode= "Forms" >
<forms loginurl= "~/home/index" timeout= "2880" >
<credentials passwordformat= "Clear" >
<user name= "name" password= "21218cca77804d2ba1922c33e0151105"/>
</credentials>
</forms>
</authentication>

-Login Success View:/shared/welcome.cshtml

@{
Viewbag.title = "Welcome";
Layout = "~/views/shared/_layout.cshtml";
}

@Html. ActionLink ("Logout", "SignOut", "Home")

Login page:

Login failed:

-If you want to use it globally

Filters. ADD (New Encryptloginattribute ());

-Remarks

Do not put the login successfully display page debug, because, when using formsauthentication.authenticate (username, md5password), prompt this method is outdated While using Membership.ValidateUser (username, md5password), the corresponding Web. config is configured and is not scrutiny.

Resources:
MVC Filters Part 3-action filter and Action Result Filter

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.