Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在asp.net mvc中为非ajax和;Ajax请求_Asp.net_Asp.net Mvc_Asp.net Mvc 5_Forms Authentication_Authorize Attribute - Fatal编程技术网

如何在asp.net mvc中为非ajax和;Ajax请求

如何在asp.net mvc中为非ajax和;Ajax请求,asp.net,asp.net-mvc,asp.net-mvc-5,forms-authentication,authorize-attribute,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 {

我在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框

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

<httpRuntime targetFramework="4.5" />
    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="2880" />
    </authentication>
    <authorization>
      <deny users="?" />
      <allow users="*" />
    </authorization>
在我的海关授权书中,我有以下信息:-

  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> 

IIS 8.0详细错误-403.0-禁止
HTTP错误403.0-禁止
您没有查看此目录或页面的权限。
最可能的原因:
  • 这是一个常见的403错误,意味着经过身份验证的用户无权查看页面。
    • 您可以尝试的事情: 有关此错误的更多信息,请查看失败的请求跟踪日志。有关详细信息,请单击
    详细错误信息: 模块ManagedPipelineHandler 通知ExecuteRequestHandler Handler System.Web.Mvc.MvcHandler 错误代码0x00000000 请求的URLhttps://localhost:44300/Rack/RackSwitch/702?X-使用=XMLHttpRequest&;请求_=1407421575424 物理路径C:\Users\…\Desktop\New folder(5)\TMS\TMS\Rack\RackSwitch\702 登录方法表单 登录用户。。。 请求跟踪目录C:\Users\…\Documents\IISExpress\TraceLogFiles\TMS 更多信息: 此一般403错误意味着经过身份验证的用户无权使用请求的资源。IIS日志文件中的子状态代码应指示403错误的原因。如果子状态代码不存在,请使用上述步骤收集有关错误源的更多信息。


并且不会显示任何警报。

在Ajax情况下,您可以通过以下方式设置AjaxError的全局设置:

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

    if(xhr.status == 401) {

      alert("Unathorized Request");

   }

})
您只需在主布局或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");

   }

})
看这里,我昨天也回答了:

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

[CheckUserPermissions]
public ActionResult SomeAction()
{

return View()

}

感谢rply,我知道我需要用我的自定义授权来修饰我的操作方法,不管请求是否为ajax,对吗??我无法理解您的观点,因为我的自定义授权将应用于所有操作方法,,,即使它们返回json>…我也尝试了您在我的母版页上定义ajaxSetup的方法,但它不起作用。。你可以确认jquery已经包含并包装在document.ready中,检查firebug控制台或chrome inspector控制台是否已经加载了错误jquery,但我认为问题是所有401请求都将被重定向到前面提到的insdie my web.config中。我不能删除它,因为如果我的用户未登录,我希望系统自动重定向到此url…您检查控制台了吗?