SoFunction
Updated on 2025-03-07

Mvc authentication, exception handling, permission verification (interceptor) implementation code

1. User login
The steps to verify whether the user is logged in successfully are ignored. How to save the current user login information (session, cookie) after the user login is successful. This article introduces identity authentication (actually based on cookies). Let’s take a look at the code below.
Introducing namespaces
using ;
Copy the codeThe code is as follows:

Users ModelUser = new Users() { ID = 10000, Name = UserName, UserName = UserName, PassWord = PassWord, Roles = "admin" };//User entity
string UserData = <Users>(ModelUser);//Serialize user entity
//Save the identity information, you can see the prompts when the parameter description is displayed
FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket(1, UserName, , (12), false, UserData);
HttpCookie Cookie = new HttpCookie(, (Ticket));//Encrypt the identity information and save it to the cookie
(Cookie);

Now the identity information is saved to the cookie. What should I do if there is a scenario where I need to use the current user's user ID or other information?
Then, we will get the identity information in the cookie again, decrypt it, and then deserialize it into the user entity.
Copy the codeThe code is as follows:

/// <summary>
/// Get user login information
/// </summary>
/// <returns></returns>
public Users GetUser()
{
if ()//Is it passed the authentication
{
HttpCookie authCookie = [];//Get cookies
FormsAuthenticationTicket Ticket = ();//Decrypt
return <Users>();//Deserialization
}
return null;
}

2. Permission verification
Here is the action interceptor in MVC (rewrite OnActionExecuting), and the code in the interceptor will be run first before the action is executed. Here you can also verify whether the identity is expired.
Copy the codeThe code is as follows:

/// <summary>
/// Permission verification
/// </summary>
public class AuthAttribute : ActionFilterAttribute
{
/// <summary>
/// Role name
/// </summary>
public string Code { get; set; }
/// <summary>
/// Verify permissions (there will be executed here before the action is executed)
/// </summary>
/// <param name="filterContext"></param>
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
//If there is identity information
if (!)
{
ContentResult Content = new ContentResult();
= ("<script type='text/javascript'>alert('Please log in first!');='{0}';</script>", );
= Content;
}
else
{
string[] Role = ().(',');//Get all roles
if (!(Code))//Verify permission
{
//The verification is not passed
ContentResult Content = new ContentResult();
= "<script type='text/javascript'>alert('Permission verification is not passed!');(-1);</script>";
= Content;
}
}
}
}

So how do you call it in action? Here is the code in HomeController to read.
Copy the codeThe code is as follows:

public class HomeController : BaseController
{
[AuthAttribute(Code = "admin")]//Verification is passed (this action only allows admin to be viewed)
public ActionResult Index()
{
Users ModelUser = ();
return View(ModelUser);
}
[AuthAttribute(Code = "user")]//The verification does not pass
public ActionResult Index2()
{
return View();
}
[AuthAttribute(Code = "admin")]//Verification passed, an exception occurred
public ActionResult Index3()
{
return View();
}
}

This way you can control permissions to action.
3. Exception handling
The above HomeController does not inherit the Controller, but a BaseController we define ourselves. So let’s take a look at what is written in the BaseController?
Copy the codeThe code is as follows:

[ErrorAttribute]
public class BaseController : Controller
{
//All Controllers inherit BaseController, exception capture will be performed
}

Here, BaseController only does one thing, which is to add an error interceptor of ErrorAttribute. Then, as long as the exception occurs in the Controller will be processed in the ErrorAttribute, you can record operations such as database. So let's see how ErrorAttribute works.
Copy the codeThe code is as follows:

/// <summary>
/// Error log (This will be executed when an exception occurs in the Controller)
/// </summary>
public class ErrorAttribute : ActionFilterAttribute, IExceptionFilter
{
/// <summary>
/// Exception
/// </summary>
/// <param name="filterContext"></param>
public void OnException(ExceptionContext filterContext)
{
//Get exception information, store it in the library
Exception Error = ;
string Message = ;//Error message
string Url = ;//The address of the error occurred
= true;
= new RedirectResult("/Error/Show/");//Skip to the error prompt page
}
}

Here you can catch the exception and then jump to the friendly error prompt page. Several operations in MVC can be completed so simply. The code will be downloaded below the article.

Example code

author: