Classic ASP.NET
On classic ASP.NET when calling a [WebMethod] with Ajax in an unauthorized context (most likely in the case where the session expired) the response http status code is 401. You can handle this in the “error” handler (provided by most Ajax frameworks) and redirect to login page. For example I use this code with jQuery:
WebMethod;
[WebMethod] public static MyModel GetStuff() { return new MyModel(); }
Javascript:
$.ajax({ type: "POST", url: "Default.aspx/GetStuff", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { // do stuff }, error: function(xhr, status, ex) { if (xhr.status == 401) // unauthorized { window.location = "Login.aspx?ReturnUrl=" + window.location.pathname; } } });
ASP.NET MVC
To do the same in ASP.NET MVC I have this method in my controller:
[Authorize] public ActionResult GetStuff() { return Json(new MyModel()); }
The ASP.NET MVC infrastructure doesn’t return 401 http status code on failed authorization but 302 http status code (actually the 401 status code is returned initially but later, in the same request, is intercepted by the infrastructure and replaced by 302 status code). XMLHttpRequest object handles this internally automatically following the redirect (no event is fired client side). The Ajax call will end in “success” but the message won’t be the expected JSON but the html of the login page.
The best (well, it’s a hack, if you a better way please tell me) way I found is to replace 302 status code by 401 status code on request end. I added the following code to Global.asax :
protected void Application_EndRequest() { if (Context.Response.StatusCode == 302 && Context.Request.Headers["X-Requested-With"] == "XMLHttpRequest") { Context.Response.Clear(); Context.Response.StatusCode = 401; } }
And the client side code (using Ext JS this time) is:
Ext.Ajax.on('requestexception', function(conn, response, options) { if (response.status == 401) { window.location = '<%= Html.ActionUrl("Account", "LogOn") %>?ReturnUrl=' + window.location.pathname; } });
Funny, I am having this same issue, in a custom handler I am working on. Your solution won’t work in my case as sometimes we will want the 302 error for other paths in the application.
Hi Ben,
Thanks for posting this up, I am currently trying to implement an MVC uploader and this post is a helpful starting point. One problem I am having with your code is that Im getting a 302 HTTP error every time I post to my controler. Any ideas on why this should be?
Thanks again,
Brian
Sorry … posted to wrong blog
Heya i’m for the first time here. I found this board and I find It truly helpful & it
helped me out much. I’m hoping to present one thing again and help others
such as you helped me.
konnicy zaś pewność na rowerze ,maluch przypadkiem mieć chęć tyłek zmniejszone w ten sposób, że jej raty płasko na ziemi, kiedy.
Heya i am for the primary time here. I found this board and I find It
really helpful & it helped me out a lot. I hope to progide
one thing back and aaid others like you helped me.
Com|squidoo|youtube|bebo|flickr|hub pages|wikipedia|tagged|facebook game|social networks|the facebook|online social networks|facebook itself} top dog grade Zuckerberg eat pledged to utilize in keeping with the ‘No Ad’ regulation. in fact, according to designer and magnificence mavens, Another awesome thing about almost all of these boots is they make our leg overall look thin together with well developed.
cheap retro jordans http://www.rethink4.com
I see you share interesting content here, you can earn some extra money, your website has big
potential, for the monetizing method, just type in google – K2
advices how to monetize a website
I read a lot of interesting articles here.
Probably you spend a lot of time writing, i know how to save you
a lot of time, there is an online tool that creates unique, SEO friendly posts in minutes,
just search in google – laranitas free content source
Every weekend i used to pay a quick visit this web site,
as i wish for enjoyment, since this this site conations in fact good funny stuff too.
Nice article 838, I fell the same way about Dotnet as this guy explained on TED http://www.youtube.com/watch?v=y3y6XMls9ns
即日必要なキャッシングは、対応してくれる金融会社をしっかりと精査して利用したほうが良いです。業態的に銀行などいろいろあります。これらは利用者の信用状態などで変わってきますが、融資を利用する場合は、口コミ情報などを考えて決定するべきです。
Hello blogger, do you monetize your site ?
There is easy method to earn extra money every day, just search on youtube : How to earn with wordai 4
If you want to get more visitors to blog.nvise.com, you should really check out this free training: http://www.3001data.com/traffic-masterclass-cm?invitation=cma&website=blog.nvise.com
I see you don’t monetize your site, don’t waste your
traffic, you can earn extra cash every month because you’ve got high quality content.
If you want to know how to make extra $$$, search for:
Boorfe’s tips best adsense alternative
Asѕim você tem como ganhar dinheiro nas redes sociais.
Hey there, You’ve done a great job. I will certainly digg it
and personally recommend to my friends. I’m confident they’ll be benefited from this web site.
thaitrade scam bangkok tuk tuk scam bangkok bar scam gem scam thailand
thailand hospital scam https://siam-shipping.com/
Zapraszam na mojego bloga KatKatMatura0098. Zdjęcia, artykuły…
Zapraszamy po przykładowe biznes plany. Dziesiątki przykładów i pomysłów na biznes.
Hello there!
You Need Leads, Sales, Conversions, Traffic for nvise.com ? Will Findet…
I WILL SEND 5 MILLION MESSAGES VIA WEBSITE CONTACT FORM
Don’t believe me? Since you’re reading this message then you’re living proof that contact form advertising works!
We can send your ad to people via their Website Contact Form.
IF YOU ARE INTERESTED, Contact us => lisaf2zw526@gmail.com
Regards,
Fielding
Zajrzyj na mojego osobistego bloga KatKatMatura0098. Fotosy, artykuły…
Thanks
Hi
I will Find Leads that Buy From You
I will Promote Your Business In Any Country To Any Niche.
==> https://is.gd/eehANy
Regards
Good day
I just checked out your website nvise.com and wanted to find out if you need help for SEO Link Building ?
If you aren’t using SEO Software then you will know the amount of work load involved in creating accounts, confirming emails and submitting your contents to thousands of websites.
With THIS SOFTWARE the link submission process will be the easiest task and completely automated, you will be able to build unlimited number of links and increase traffic to your websites which will lead to a higher number of customers and much more sales for you.
IF YOU ARE INTERESTED, We offer you 7 days free trial
==> http://bit.ly/Robot_Submitter
Kind Regards,
Bryant Rigg ! Business Development Manager
Zapraszam wszystkich do odwiedzenia mojej nowej strony http://www.analiza-swot.org. Znajdziecie tam artykuły z tematyki biznesowej, ekonomicznej, marketingowej….
I WILL FIND POTENTIAL CUSTOMERS FOR YOU
I’m talking about a better promotion method than all that exists on the market right now, even better than email marketing.
Just like you received this message from me, this is exactly how you can promote your business or product.
CLAIM YOUR FREE TEST (Contact me)
Skype ID : (live:.cid.5554a4758747b4a5)
Email: (ventfara@mail.com)
Great post. It’s good that you bring up this topic. It will be useful for a lecture to high school. Thanks! ps. I invite you to visit my website satik.pl Articles are in Polish, but maybe there is someone who understands this language
I visit daily some blogs and sites to read articles,
however this webpage provides feature based writing.
Excellent beat ! I wish to apprentice while you amend your site, how can i
subscribe for a blog website? The account aided me a appropriate deal.
I were tiny bit familiar of this your broadcast offered vibrant transparent idea
I think the admin of this site is actually working hard in support of his site, because here every material is quality based material.
Hi to every one, because I am genuinely keen of reading this
weblog’s post to be updated daily. It carries nice stuff.
wonderful publish, very informative. I ponder why the other experts of this sector do not notice
this. You must proceed your writing. I’m confident, you have a huge readers’ base already!
My relatives always say that I am wasting my time
here at net, except I know I am getting know-how every day by reading
such good posts.
Wonderful beat ! I wish to apprentice while you amend your web site,
how can i subscribe for a blog web site? The account aided me a acceptable deal.
I had been tiny bit acquainted of this your broadcast offered bright clear concept
Hey there, You’ve done an excellent job. I will certainly digg
it and personally recommend to my friends. I am confident they’ll
be benefited from this site.
I love it whenever people come together and share ideas.
Great site, stick with it!
For newest information you have to go to see internet and on internet I found this website as a best web site for most recent updates.
bookmarked!!, I love your site!
I was curious if you ever thought of changing the layout of your site?
Its very well written; I love what youve got
to say. But maybe you could a little more in the way of content so people could
connect with it better. Youve got an awful lot of text for
only having one or two pictures. Maybe you could space it out better?
Simply want to say your article is as astonishing.
The clarity for your put up is simply nice and i could
assume you’re a professional in this subject. Fine together
with your permission allow me to seize your feed to keep up
to date with coming near near post. Thanks 1,000,000 and please carry on the enjoyable work.
It’s an awesome piece of writing designed for all the web
viewers; they will obtain benefit from it I am sure.
I blog frequently and I genuinely thank you for your information. Your article has truly peaked my interest.
I am going to take a note of your site and keep checking for new information about once a week.
I opted in for your Feed too.
I reckon something truly interesting about your web site so I saved to my bookmarks . Bliss Wendel Balthasar
What’s up, for all time i used to check webpage posts here
early in the daylight, because i enjoy to gain knowledge of more and more.
Have you ever thought about adding a little bit more than just your articles? I mean, what you say is important and all. However think about if you added some great photos or videos to give your posts more, “pop”! Your content is excellent but with pics and video clips, this blog could definitely be one of the greatest in its niche. Very good blog!
Really appreciate you sharing this article post. Much thanks again. Great. Rory Durant Stuppy
Hello, after reading this remarkable article i am as well glad to share my knowledge here with friends.
can i bring a the pen vape on a cruise
Hello! I know this is kinda off topic however I’d figured I’d ask.
Would you be interested in trading links or maybe guest authoring a
blog article or vice-versa? My blog addresses a lot of the same topics
as yours and I believe we could greatly benefit from each other.
If you might be interested feel free to send me an e-mail.
I look forward to hearing from you! Awesome blog by the way!
I do accept as true with all of the ideas you have introduced on your
post. They are very convincing and will certainly work.
Still, the posts are very quick for newbies. May you please extend them a bit from subsequent time?
Thank you for the post.
An impressive share! I’ve just forwarded this onto a co-worker who was doing
a little homework on this. And he actually bought me lunch because
I discovered it for him… lol. So allow me to reword this….
Thanks for the meal!! But yeah, thanks for spending time to talk about this subject here on your
blog.
Hey! This post could not be written any better! Reading through this
post reminds me of my previous room mate! He always kept talking about this.
I will forward this post to him. Pretty sure
he will have a good read. Many thanks for sharing!
hello!,I really like your writing very much!
share we communicate extra approximately your post on AOL?
I need an expert in this house to resolve my problem. Maybe that is you!
Taking a look ahead to look you.
I have fun with, cause I discovered just what I used to
be having a look for. You’ve ended my 4 day long hunt! God Bless
you man. Have a great day. Bye
Hey this is kinda of off topic but I was wanting to
know if blogs use WYSIWYG editors or if you have to manually code with HTML.
I’m starting a blog soon but have no coding knowledge so I wanted to get guidance from someone with experience.
Any help would be greatly appreciated!
Thanks for your posting on this site. From my own personal experience, occasionally softening up a photograph may provide the digital photographer with a little bit of an inspired flare. Often however, the soft clouds isn’t just what exactly you had at heart and can quite often spoil an otherwise good photograph, especially if you intend on enlarging the item.
Undeniably believe that which you said. Your favourite reason seemed to be on the
net the simplest factor to understand of. I say to
you, I certainly get irked while folks consider issues that they plainly don’t recognise about.
You managed to hit the nail upon the top and outlined out the entire thing without having side-effects
, people could take a signal. Will likely be back to get more.
Thank you