一、防止跨站脚本攻击(XSS)
①: @Html.Encode("<script>alert(‘123‘)</script>")
编码后:<script>alert('123')</script>
②: @Html.AttributeEncode("<script>alert(‘123‘)</script>")
编码后:<script>alert('123')</script>
③: @Html.JavascriptEncode()
③: 使用antixss库防御
二、防止跨站请求伪造(CSRF)
①: 令牌验证(用于表单验证)
在提交表单中加上@Html.AntiForgeryToken(),在控制器中加上[ValidateAntiforgeryToken]
②: HttpReferrer验证(get、post)
新建一个类,继承AuthorizeAttribute(在提交的时候验证):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace SchoolManageDomw.Models
{
    public class IsPostedThisSiteAttribute:AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext.HttpContext != null)
            {
                if (filterContext.HttpContext.Request.UrlReferrer == null)
                    throw new Exception("客户端请求的信息为空");
                if (filterContext.HttpContext.Request.UrlReferrer.Host != "localhost")//MySite.com
                    throw new Exception("不安全的请求");
            }
        }
    }
}控制器里使用:
        [IsPostedThisSite]
        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }
本文出自 “程序猿的家--Hunter” 博客,请务必保留此出处http://962410314.blog.51cto.com/7563109/1606025
原文:http://962410314.blog.51cto.com/7563109/1606025