Showing posts with label ASP.NET MVC. Show all posts
Showing posts with label ASP.NET MVC. Show all posts

Monday, June 27, 2016

How to return a 401 status code using ASP.NET MVC 5 and OWIN

This time I was trying to force users to the login page after an Ajax request failed because of an expired session. I was getting something like this in the response:

X-Responded-JSON: {"status":401,"headers":...
  
I investigated a little and turned out you have to add this code to your Startup.Auth.cs file:

Provider = new CookieAuthenticationProvider
{
  OnApplyRedirect = ctx =>
  {
    if (!IsAjaxRequest(ctx.Request))
    {
       ctx.Response.Redirect(ctx.RedirectUri);
    }
  }
}

Also, in your filter I suggest you do something like this:


if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Items["RequestWasNotAuthorized"] = true;
filterContext.HttpContext.Response.StatusCode = 401;
filterContext.HttpContext.Response.End();
filterContext.Result = new HttpUnauthorizedResult();
}


And then handle it in JavaScript like this:

$(document).ajaxError(function (xhr, props) {
if (props.status === 401) {
location.reload();
}
});


More information on the error can be found here:
http://kevin-junghans.blogspot.mx/2013/12/returning-401-http-status-code-on.html
https://brockallen.com/2013/10/27/using-cookie-authentication-middleware-with-web-api-and-401-response-codes/

Saturday, June 18, 2011

Catching authorization errors with JQuery when using Forms Authentication in ASP.NET MVC 3

When there's an authentication error (timeout or invalid credentials) in ASP.NET MVC 3, the framework returns the login pages as a result of this. What if you want to catch the error in JQuery and handle it client side. Well, you can't. Unless, of course, you read this article.

Wednesday, April 6, 2011

Improving performance on ASP.NET websites

I came across this interesting article with a checklist to improve the performance of ASP.NET websites. The ideas presented in the article are nothing new, but they are provided in such a way that you can check if your website passes or not.

But remember, don't worry about performance until it becomes an issue.

Friday, October 1, 2010

ASP.NET MVC 2 application doesn't work on IIS 6.0

Nowadays we expect things to just work. I deployed an ASP.NET MVC 2 application on IIS 6.0 and it didn't work at first. I can't remember the exact error, but it was something about the page not being found. After googling the error -and finding a lot of confusing information-, I decided to try http://www.asp.net/. I found the solution on this tutorial.

By the way, what is it with not being able to download ASP.NET MVC 2 from http://www.asp.net/. It's just dumb, being the "official" page to learn ASP.NET MVC, it should have a link to download it.