如何控制我的asp.net mvc中的401 http响应,用于非ajax和amp; Ajax请求

时间:2014-08-07 10:49:21

标签: asp.net asp.net-mvc asp.net-mvc-5 forms-authentication authorize-attribute

我在asp.net mvc 4 Web应用程序中创建了以下自定义授权属性。

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]

    public class CheckUserPermissionsAttribute : AuthorizeAttribute
    {

        public string Model { get; set; }
        public string Action { get; set; }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            if (!httpContext.Request.IsAuthenticated)
                return false;

            int value = 0;
            Repository repository = new Repository();

            string ADusername = httpContext.User.Identity.Name.Substring(httpContext.User.Identity.Name.IndexOf("\\") + 1);
            if (!repository.can(ADusername, Model, value)) // implement this method based on your tables and logic
            {

                return false;

            }
            return true;


        }
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {

            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {

                var viewResult = new JsonResult();
                viewResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;

                viewResult.Data = (new { IsSuccess = "Unauthorized", description = "Sorry, you do not have the required permission to perform this action." });
                filterContext.HttpContext.Response.StatusCode = 401;
                filterContext.Result = viewResult;

            }
            else
            {
                var viewResult = new ViewResult();

                viewResult.ViewName = "~/Views/Errors/_Unauthorized.cshtml";
                filterContext.HttpContext.Response.StatusCode = 401;
                filterContext.Result = viewResult;
            }

         //   base.HandleUnauthorizedRequest(filterContext);
        }
    }

我要做的是将所有非Ajax请求重定向到自定义错误页面,而如果请求是Ajax则返回一个json对象,然后显示包含json数据的jAlert框。 / p>

在我的web.config中,我有以下内容: -

<httpRuntime targetFramework="4.5" />
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="2880" />
    </authentication>
    <authorization>
      <deny users="?" />
      <allow users="*" />
    </authorization>

但我有以下问题: -

  1. 从那里我可以定义当我的自定义授权属性返回401以重定向到视图时,如果请求是非Ajax?如果请求是Ajax来显示JAlert框?对于Ajax请求,我知道我可以定义一个onfailure脚本,它将显示一个jalert。但是我想避免为每个Ajax函数执行此操作并在一个地方定义此设置?
  2. 由于

    修改

    目前我正在做以下事情; 我在我的通用脚本中定义了这个: -

    $(document).ready(function () {
        $.ajaxSetup(
    
            {
    
            type: "POST",
            cache: false,
            error: function (xhr, statusText, err) {
                alert("Error:" + xhr.status);
            }
        });
    
    $.ajaxSetup({
    
            type: "GET",
            cache: false,
            error: function (xhr, statusText, err) {
                alert("Error:" + xhr.status);
            }
        });
    

    在我的自定义授权中,我有以下内容: -

      protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
            {
    
                if (filterContext.HttpContext.Request.IsAjaxRequest())
                {
    
                    var viewResult = new JsonResult();
                    viewResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
    
                   // viewResult.Data = (new { IsSuccess = "Unauthorized", description = "Sorry, you do not have the required permission to perform this action." });
                    filterContext.HttpContext.Response.StatusCode = 403;
                    filterContext.Result = viewResult;
    
                }
                else
                {
                    var viewResult = new ViewResult();
    
                    viewResult.ViewName = "~/Views/Errors/_Unauthorized.cshtml";
                    filterContext.HttpContext.Response.StatusCode = 403;
                    filterContext.Result = viewResult;
                }
    
             //   base.HandleUnauthorizedRequest(filterContext);
            }
    

    但是目前如果我点击ajax链接并且我没有获得授权,我将使用firebug得到以下回复: -

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 
    <html xmlns="http://www.w3.org/1999/xhtml"> 
    <head> 
    <title>IIS 8.0 Detailed Error - 403.0 - Forbidden</title> 
    <style type="text/css"> 
    <!-- 
    body{margin:0;font-size:.7em;font-family:Verdana,Arial,Helvetica,sans-serif;} 
    code{margin:0;color:#006600;font-size:1.1em;font-weight:bold;} 
    .config_source code{font-size:.8em;color:#000000;} 
    pre{margin:0;font-size:1.4em;word-wrap:break-word;} 
    ul,ol{margin:10px 0 10px 5px;} 
    ul.first,ol.first{margin-top:5px;} 
    fieldset{padding:0 15px 10px 15px;word-break:break-all;} 
    .summary-container fieldset{padding-bottom:5px;margin-top:4px;} 
    legend.no-expand-all{padding:2px 15px 4px 10px;margin:0 0 0 -12px;} 
    legend{color:#333333;;margin:4px 0 8px -12px;_margin-top:0px; 
    font-weight:bold;font-size:1em;} 
    a:link,a:visited{color:#007EFF;font-weight:bold;} 
    a:hover{text-decoration:none;} 
    h1{font-size:2.4em;margin:0;color:#FFF;} 
    h2{font-size:1.7em;margin:0;color:#CC0000;} 
    h3{font-size:1.4em;margin:10px 0 0 0;color:#CC0000;} 
    h4{font-size:1.2em;margin:10px 0 5px 0; 
    }#header{width:96%;margin:0 0 0 0;padding:6px 2% 6px 2%;font-family:"trebuchet MS",Verdana,sans-serif; 
     color:#FFF;background-color:#5C87B2; 
    }#content{margin:0 0 0 2%;position:relative;} 
    .summary-container,.content-container{background:#FFF;width:96%;margin-top:8px;padding:10px;position:relative;} 
    .content-container p{margin:0 0 10px 0; 
    }#details-left{width:35%;float:left;margin-right:2%; 
    }#details-right{width:63%;float:left;overflow:hidden; 
    }#server_version{width:96%;_height:1px;min-height:1px;margin:0 0 5px 0;padding:11px 2% 8px 2%;color:#FFFFFF; 
     background-color:#5A7FA5;border-bottom:1px solid #C1CFDD;border-top:1px solid #4A6C8E;font-weight:normal; 
     font-size:1em;color:#FFF;text-align:right; 
    }#server_version p{margin:5px 0;} 
    table{margin:4px 0 4px 0;width:100%;border:none;} 
    td,th{vertical-align:top;padding:3px 0;text-align:left;font-weight:normal;border:none;} 
    th{width:30%;text-align:right;padding-right:2%;font-weight:bold;} 
    thead th{background-color:#ebebeb;width:25%; 
    }#details-right th{width:20%;} 
    table tr.alt td,table tr.alt th{} 
    .highlight-code{color:#CC0000;font-weight:bold;font-style:italic;} 
    .clear{clear:both;} 
    .preferred{padding:0 5px 2px 5px;font-weight:normal;background:#006633;color:#FFF;font-size:.8em;} 
    --> 
    </style> 
    
    </head> 
    <body> 
    <div id="content"> 
    <div class="content-container"> 
      <h3>HTTP Error 403.0 - Forbidden</h3> 
      <h4>You do not have permission to view this directory or page.</h4> 
    </div> 
    <div class="content-container"> 
     <fieldset><h4>Most likely causes:</h4> 
      <ul>  <li>This is a generic 403 error and means the authenticated user is not authorized to view the page.</li> </ul> 
     </fieldset> 
    </div> 
    <div class="content-container"> 
     <fieldset><h4>Things you can try:</h4> 
      <ul>  <li>Check the failed request tracing logs for additional information about this error. For more information, click <a href="http://go.microsoft.com/fwlink/?LinkID=66439">here</a>. </li> </ul> 
     </fieldset> 
    </div> 
    
    <div class="content-container"> 
     <fieldset><h4>Detailed Error Information:</h4> 
      <div id="details-left"> 
       <table border="0" cellpadding="0" cellspacing="0"> 
        <tr class="alt"><th>Module</th><td>&nbsp;&nbsp;&nbsp;ManagedPipelineHandler</td></tr> 
        <tr><th>Notification</th><td>&nbsp;&nbsp;&nbsp;ExecuteRequestHandler</td></tr> 
        <tr class="alt"><th>Handler</th><td>&nbsp;&nbsp;&nbsp;System.Web.Mvc.MvcHandler</td></tr> 
        <tr><th>Error Code</th><td>&nbsp;&nbsp;&nbsp;0x00000000</td></tr> 
    
       </table> 
      </div> 
      <div id="details-right"> 
       <table border="0" cellpadding="0" cellspacing="0"> 
        <tr class="alt"><th>Requested URL</th><td>&nbsp;&nbsp;&nbsp;https://localhost:44300/Rack/RackSwitch/702?X-Requested-With=XMLHttpRequest&amp;_=1407421575424</td></tr> 
        <tr><th>Physical Path</th><td>&nbsp;&nbsp;&nbsp;C:\Users\...\Desktop\New folder (5)\TMS\TMS\Rack\RackSwitch\702</td></tr> 
        <tr class="alt"><th>Logon Method</th><td>&nbsp;&nbsp;&nbsp;Forms</td></tr> 
        <tr><th>Logon User</th><td>&nbsp;&nbsp;&nbsp;...</td></tr> 
        <tr class="alt"><th>Request Tracing Directory</th><td>&nbsp;&nbsp;&nbsp;C:\Users\.....\Documents\IISExpress\TraceLogFiles\TMS</td></tr> 
       </table> 
       <div class="clear"></div> 
      </div> 
     </fieldset> 
    </div> 
    
    <div class="content-container"> 
     <fieldset><h4>More Information:</h4> 
      This generic 403 error means that the authenticated user is not authorized to use the requested resource. A substatus code in the IIS log files should indicate the reason for the 403 error. If a substatus code does not exist, use the steps above to gather more information about the source of the error. 
      <p><a href="http://go.microsoft.com/fwlink/?LinkID=62293&amp;IIS70Error=403,0,0x00000000,7601">View more information &raquo;</a></p> 
    
     </fieldset> 
    </div> 
    </div> 
    </body> 
    </html> 
    

    并且不会显示任何警报..

1 个答案:

答案 0 :(得分:2)

在Ajax情况下,您可以这样设置AjaxError的全局设置:

您只需要在主布局或js文件中编写一次并将其包含在母版页中,只要应用程序中的ajax调用失败,就会调用它:

$.ajaxSetup({

 error: function (x, e) {

     if (x.status == 401) {

         alert("Unauthorized Access");

}

 });

});

或者您可以这样写 ajaxError 事件:

$(document).ajaxError(function(xhr, statusText, err){

    if(xhr.status == 401) {

      alert("Unathorized Request");

   }

})

请看这里我昨天也回答: How require authorization within whole ASP .NET MVC application

对于正常(非ajax请求),您必须使用您的属性修饰操作或控制器:

[CheckUserPermissions]
public ActionResult SomeAction()
{

return View()

}