هدایت خودکار کاربر به صفحه لاگین در حین اعمال Ajax ایی
نویسنده: وحید نصیری
تاریخ: ۱۳۹۱/۰۹/۲۴ ۱۳:۱۷
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
using System;
using System.Net;
using System.Web.Mvc;
namespace MvcApplication28.Helpers
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public sealed class SiteAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAuthenticated)
{
throw new UnauthorizedAccessException(); //to avoid multiple redirects
}
else
{
handleAjaxRequest(filterContext);
base.HandleUnauthorizedRequest(filterContext);
}
}
private static void handleAjaxRequest(AuthorizationContext filterContext)
{
var ctx = filterContext.HttpContext;
if (!ctx.Request.IsAjaxRequest())
return;
ctx.Response.StatusCode = (int)HttpStatusCode.Forbidden;
ctx.Response.End();
}
}
}
using System.Web.Mvc;
using MvcApplication28.Helpers;
namespace MvcApplication28.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[SiteAuthorize]
[HttpPost]
public ActionResult SaveData(string data)
{
if(string.IsNullOrWhiteSpace(data))
return Content("NOk!");
return Content("Ok!");
}
}
}
@{
ViewBag.Title = "Index";
var postUrl = this.Url.Action(actionName: "SaveData", controllerName: "Home");
}
<h2>
Index</h2>
@using (Html.BeginForm(actionName: "SaveData", controllerName: "Home",
method: FormMethod.Post, htmlAttributes: new { id = "form1" }))
{
@Html.TextBox(name: "data")
<br />
<span id="btnSave">Save Data</span>
}
@section Scripts
{
<script type="text/javascript">
$(document).ready(function () {
$("#btnSave").click(function (event) {
$.ajax({
type: "POST",
url: "@postUrl",
data: $("#form1").serialize(),
// controller is returning a simple text, not json
complete: function (xhr, status) {
var data = xhr.responseText;
if (xhr.status == 403) {
window.location = "/login";
}
}
});
});
});
</script>
}
filterContext.Result = new JavaScriptResult { Script="window.location = '" + redirectToUrl + "'"};
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new SiteAuthorizeAttribute());
}
window.location = "/login";
function getLoginUrl() {
var localParentUrl = window.location.href.replace(window.location.origin, "");
var redirectUrl = window.location.origin + "/Login?ReturnUrl=" + encodeURIComponent(localParentUrl);
return redirectUrl;
}