سؤال

I have an authorization filter class:

public class ValidateSessionTokenFilter : IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationContext filterContext)
    {
        if (filterContext.HttpContext.Request.IsAjaxRequest())
        {
            filterContext.Result = new JsonResult
            {
                Data = new { Message = "Session timeout" },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
            filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
        }
    }
}

The filter works, but the problem is that even if i force the return type to be a JsonResult result, the framework always returns a redirect to login page.

Is there any way of preventing this behavior?

هل كانت مفيدة؟

المحلول

That's the default behaviour of Forms Authentication when you return a 401. Afaik there's no setting to disable that behavior in .Net < 4.5 so, the workaround besides using your own auth system, is something like this: - return a custom code (something like 4100) - hook up on the EndRequest event then check it out

if (context.Response.StatusCode==4100)
 {
       context.Response.StatusCode=401;
  }

نصائح أخرى

It is a MVC issue with HttpStatusCode.Unauthorized, it always do redirect. We "fix" this issue with returning custom error code.

p.s. If you really need this I can find code witch is responsible for this.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top