In the previous article we've learned about action filter and the built-in filter implementation, and now we're going to write an instance. Just write a filter for the anti-theft chain.
First inherits from the FilterAttribute class implements the Iactionfilter interface simultaneously, the code is as follows:
<summary>
Anti-theft chain filter.
</summary>
public class Antioutsitelinkattribute:actionfilterattribute, Iactionfilter
{
Public Antioutsitelinkattribute (FileType FileType)
{
This. FileType = FileType;
}
<summary>
The requested file type. (file or picture)
</summary>
Public FileType FileType{get; set;}
Iactionfilter Members
<summary>
Get the root domain name of the site
</summary>
<param name= "domain" > website, without "http.//" </param>
<returns></returns>
private string Getrootdomain (string domain)
{
if (string. IsNullOrEmpty (domain))
{
throw new ArgumentNullException ("parameter ' domain ' cannot be empty");
}
string[] arr = domain. Split (new[){'. '}, Stringsplitoptions.removeemptyentries);
if (arr. Length <= 2)
{
return domain;
}
Else
{
Return Arr[arr. Length-2] + "." + Arr[arr. LENGTH-1];
}
}
}
public enum FileType
{
File = 1,
Image
}
We then set up a controller to process the file request and apply the filter that we just created:
public class Filescontroller:basecontroller
{
[Antioutsitelink (Filetype.image)]
Public ActionResult Image (string file)
{
Return Content ("Image from 4mvc");
}
[Antioutsitelink (Filetype.file)]
Public actionresult file (string file)
{
Return Content ("File from 4mvc");
}
}
A simple test:
The application of Actionfilter is very extensive, which requires you to use it flexibly. For other applications, you can refer to my previously translated ASP. NET MVC Action Filter-cache and compress this article.
Go Introduction to ASP. 10, Action filter with built-in filter implementation (instance-anti-theft chain)