MVC4 验证权限验证


权限验证

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication4
{
    public class LoginFilter : System.Web.Mvc.ActionFilterAttribute
    {
        public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            if (true)
            {
                try
                {
                    bool reqType = AjaxRequestExtensions.IsAjaxRequest(filterContext.RequestContext.HttpContext.Request);
                    if (reqType)
                    {
                        filterContext.Result = new HttpStatusCodeResult(System.Net.HttpStatusCode.Forbidden);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            }


        }
    }
}

控制器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication4.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

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

        [LoginFilter]
        public ActionResult TT()
        {
            return View();
        }

    }
}

请求页面

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<input type="button" value="测试" id="test" />

@section scripts{

    <script>
        $(function () {
            $('#test').click(function () {
                $.ajax({
                    url: '@Url.Action("TT")',
                    error: function (req) {
                        if (req.status == 403) {
                            alert("无权访问");
                        }
                    }
                });
            });
        });
    </script>

}

知识共享许可协议
《MVC4 Ajax请求权限验证》 常伟华 创作。
本作品采用知识共享署名-相同方式共享 4.0 国际许可协议 | 3.0 中国大陆许可协议进行许可。

站内公告

A PHP Error was encountered

Severity: Core Warning

Message: PHP Startup: zip: Unable to initialize module Module compiled with module API=20060613 PHP compiled with module API=20090626 These options need to match

Filename: Unknown

Line Number: 0

Backtrace: