Asp.net MVC学习日记六(过滤黑名单,使其无法访问)

1、Global.asax添加

routes.MapRoute("BlacklistFilter", "{*path}",new { controller = "Blacklist", action = "Index" },
new { isBlacklisted = new BlacklistConstraint() }
);

2、Models文件下新建BlacklistConstraint类,使其继承IRouteConstraint

public class BlacklistConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
bool blacklisted = false;
//you could get your blacklist data from a database
//and cache it when the app starts
//ip address list
List<string> _ipBlacklist = new List<string>()
{
"127.0.0.1",
"192.168.1.100",
"192.168.1.101",
"192.168.1.102",
"192.168.1.103",
"192.168.1.104",
"192.168.1.105",
"192.168.1.106",
"192.168.1.107",
"192.168.1.108",
"192.168.1.109",
"192.168.1.110"
};
//username list
List<string> _usernameBlacklist = new List<string>()
{
"asiemer",
"anonymous"
};

//email list
List<string> _emailBlacklist = new List<string>()
{
"[email protected]",
"[email protected]"
};


//check ip addresses
if (_ipBlacklist.Contains(httpContext.Request.UserHostAddress))
{

values.Add("reason", "You were blacklisted because of your IP address: " + httpContext.Request.UserHostAddress);
blacklisted = true;
}
//check usernames
if (httpContext.Profile != null && _usernameBlacklist.Contains(
httpContext.Profile.UserName.ToLower()))
{
values.Add("reason", "You were blacklisted because of your username: " + httpContext.Profile.UserName.ToLower());
blacklisted = true;
}
//check email addresses
if (_emailBlacklist.Contains("values['email'].ToString()"))
{
values.Add("reason", "You were blacklisted because of your email address: values['email'].ToString()");
blacklisted = true;
}

//do some stuff before booting the user
//if (blacklisted)
//{
// //of, if you don't want to keep them around...

// httpContext.Response.Redirect("http://www.peopleofwalmart.com");
// //set the status code to access denied
// httpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden;
//}
//return the result
return blacklisted;
}
}

3、新建BlacklistController和对应视图

public class BlacklistController : Controller
{
//
// GET: /Blacklist/

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

}

4、视图里添加以下代码

<h2>Uh oh!</h2>
<div>
It looks like you have been blacklisted. If you feel that you are seeing this mistakenly
please contact us at...
</div>
<fieldset>
<legend>Why was I blacklisted?</legend>
<%= ViewData["reason"]%>

</fieldset>

ok.只是好像页面无法显示ViewData["reason"]的值,我还没想明白为什么

你可能感兴趣的:(asp.net)