处理会话超时时,Ajax调用C#MVC控制器不工作 [英] Handling session time out when ajax call to C# mvc controller not working

查看:145
本文介绍了处理会话超时时,Ajax调用C#MVC控制器不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当调用从阿贾克斯的功能。程序流程不认可过期的会话即不重定向到登录页面。替代的是,它保存记录。我在C#.net MVC工作。那么,如何处理在阿贾克斯呼叫会话。在这里,我给我的codeS。

  $阿贾克斯({
            键入:POST,
            网址:'/员工/ SaveEmployee',
            数据:
            {
                位置:$(#txtLocation)VAL()。
                dateApplied:$(#txtDateApplied)VAL()
                状态:$(#ddStatus)VAL()。
                MAILCHECK:$(#ddMailCheck)VAL()
                ...
                ...
                ...
            },
            成功:函数(结果)
            {            },
            错误:函数(MSG)
            {
            }
      });

下面控制器

  [授权]
公共字符串SaveEmployee(字符串位置,串dateApplied,串状态,串MAILCHECK,...)
{
      objEmpMain.FirstName =名字;
      objEmpMain.LastName = lastName的;
      objEmpMain.Initial =初始;
      objEmpMain.Address1 =地址;
      ...
      ...
      ...
}


解决方案

您的AJAX调用仍然有可能最终出现成功的结果(虽然,不用担心,它不会真正执行你的操作方法),并调用你的成功处理程序。这是因为你期望的HTML,那就是你收到了什么(虽然,生成的HTML可能是您的登录页面,而不是你想要的HTML)。顺便说一句,如果你希望JSON(使用数据类型:'JSON'),这将引发一个错误,因为它会被解析HTML作为JSON

您需要做的是重定向的登录页面的AJAX请求prevent FormsAuth。现在, AuthorizeAttribute 忠实地返回 NotAuthorizedResult ,它发送一个HTTP 401未授权响应给客户端,这是理想的您的AJAX客户。

问题在于FormsAuth模块检查状态code和如果它是401,它执行重定向。我在这样combatted此问题:

1)创建我自己的衍生型 AuthorizeAttribute 的是放置一个标志 HttpContext.Items 让我知道授权失败,我就强迫401,而不是重定向:

 公共类AjaxAuthorizeAttribute:AuthorizeAttribute
{
    ///<总结>
    ///流程失败授权的HTTP请求。
    ///< /总结>
    ///< PARAM NAME =filterContext>封装的信息使用与LT;见CREF =T:System.Web.Mvc.AuthorizeAttribute/取代。在< paramref NAME =filterContext/>对象包含控制器,HTTP上下文,请求上下文,作用的结果,和路由数据< /参数>
    保护覆盖无效HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        如果(filterContext.HttpContext.Request.IsAjaxRequest())filterContext.HttpContext.Items [AjaxPermissionDenied] =真;        base.HandleUnauthorizedRequest(filterContext);
    }
}

2)添加到您的Global.asax.cs:

 保护无效Application_EndRequest(对象发件人,EventArgs的发送)
    {
        如果(Context.Items [AjaxPermissionDenied]是布尔)
        {
            Context.Response.Status code = 401;
            Context.Response.End();
        }
     }

3)状态code处理程序添加到您的jQuery AJAX设置:

  $。ajaxSetup({
    状态code:{
        401:功能(){
            window.location.href =路径/要/登录;
        }
    }
});

4)改变你想要这种行为使用 AuthorizeAttribute AjaxAuthorizeAttribute 的控制器或动作:

  [AjaxAuthorize]
公共字符串SaveEmployee(字符串位置,串dateApplied,串状态,串MAILCHECK,...)
{
      objEmpMain.FirstName =名字;
      objEmpMain.LastName = lastName的;
      objEmpMain.Initial =初始;
      objEmpMain.Address1 =地址;
      ...
      ...
      ...
}

When calling a function from ajax. Program flow does not recognized the expired session i.e not redirect to the login page. Instead of that, it saves the record. I am working in c# .net mvc. So how can i handle session while ajax call. Here i gave my codes.

 $.ajax({ 
            type: "POST",
            url:'/Employee/SaveEmployee',
            data:
            {
                Location:$("#txtLocation").val(), 
                dateApplied:$("#txtDateApplied").val(), 
                Status:$("#ddStatus").val(), 
                mailCheck:$("#ddMailCheck").val(),
                ...
                ...
                ... 
            },
            success: function (result) 
            {

            },
            error: function (msg) 
            {
            }
      });

Here the controller

[Authorize]
public string SaveEmployee(string Location, string dateApplied, string Status, string mailCheck, ...)
{
      objEmpMain.FirstName = firstName;
      objEmpMain.LastName = lastName;
      objEmpMain.Initial = Initial;
      objEmpMain.Address1 = Address;
      ...
      ... 
      ...
} 

解决方案

The result of your AJAX call will still likely end up appearing successful (although, don't worry, it won't actually execute your action method), and invoke your success handler. This is because you are expecting HTML, and that is what you are receiving (albeit, the resulting HTML is likely your login page, and not the HTML you wanted). As an aside, if you expected JSON (using dataType:'JSON'), it would trigger an error, because it would be parsing HTML as JSON.

What you need to do is prevent FormsAuth from redirecting the login page for AJAX requests. Now, AuthorizeAttribute faithfully returns a NotAuthorizedResult, which sends an HTTP 401 Not Authorized response to the client, which is ideal for your AJAX client.

The problem is that FormsAuth module checks the StatusCode and if it is 401, it performs the redirect. I've combatted this issue in this way:

1) Create my own derivative type of AuthorizeAttribute that places a flag inHttpContext.Items to let me know authorization failed, and I should force a 401 rather than a redirect:

public class AjaxAuthorizeAttribute : AuthorizeAttribute
{
    /// <summary>
    /// Processes HTTP requests that fail authorization.
    /// </summary>
    /// <param name="filterContext">Encapsulates the information for using <see cref="T:System.Web.Mvc.AuthorizeAttribute"/>. The <paramref name="filterContext"/> object contains the controller, HTTP context, request context, action result, and route data.</param>
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest()) filterContext.HttpContext.Items["AjaxPermissionDenied"] = true;

        base.HandleUnauthorizedRequest(filterContext);
    }
}

2) Add to your Global.asax.cs:

    protected void Application_EndRequest(Object sender, EventArgs e)
    {
        if (Context.Items["AjaxPermissionDenied"] is bool)
        {
            Context.Response.StatusCode = 401;
            Context.Response.End();
        }
     }

3) Add a statusCode handler to your jQuery AJAX setup:

$.ajaxSetup({
    statusCode: {
        401: function() {
            window.location.href = "path/to/login";
        }
    }
});

4) Change the controllers or actions where you want this behavior from using AuthorizeAttribute to AjaxAuthorizeAttribute:

[AjaxAuthorize]
public string SaveEmployee(string Location, string dateApplied, string Status, string mailCheck, ...)
{
      objEmpMain.FirstName = firstName;
      objEmpMain.LastName = lastName;
      objEmpMain.Initial = Initial;
      objEmpMain.Address1 = Address;
      ...
      ... 
      ...
} 

这篇关于处理会话超时时,Ajax调用C#MVC控制器不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆