在Asp.net MVC2中通过Ajax调用处理UnauthorizedRequest,可以采用以下步骤:
public class CustomUnauthorizedRequestAttribute : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext.Result is HttpUnauthorizedResult)
{
filterContext.Result = new JsonResult
{
Data = new { success = false, message = "Unauthorized" },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
filterContext.HttpContext.Response.StatusCode = 401;
}
}
}
[CustomUnauthorizedRequest]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult AjaxMethod()
{
if (!User.Identity.IsAuthenticated)
{
return new HttpUnauthorizedResult();
}
// Do something
return Json(new { success = true, message = "Success" }, JsonRequestBehavior.AllowGet);
}
}
$.ajax({
url: "/Home/AjaxMethod",
type: "GET",
dataType: "json",
success: function (data) {
if (data.success) {
// Do something
} else {
// Handle unauthorized
}
},
error: function (xhr, textStatus, errorThrown) {
if (xhr.status === 401) {
// Handle unauthorized
}
}
});
通过以上步骤,可以在Asp.net MVC2中通过Ajax调用处理UnauthorizedRequest。
领取专属 10元无门槛券
手把手带您无忧上云