ASP.NET MVC and Ajax, concurrent requests? - asp.net-mvc

AJAX newbie here!
At the moment in my ASP.NET MVC web app my AJAX requests appear to be getting batched or queued, im not sure.
No requests seem to be getting completed until the previous request has finished.
How do I go about getting the requests to return independantly?
I dont necessarily want someone to give me the answer but maybe some links to good tutorials or resources which could help. Thanks

I'm expanding on Lachlan Roche's answer, which is correct.
The ASP.NET framework will "single-thread" requests that deal with Session scope (a global resource), to prevent one request from interfering with another. In WebForms I think you can use the Page directive to specify that individual pages don't use Session and therefore don't need to treated synchronously like this.
The problem is that in ASP.NET MVC all requests use Session, because it's used to implement TempData. You can disable session state entirely, as Lachlan Roche pointed out, or you can deal with this on a case-by-case basis.
A possible solution might be to kick off your own background threads to process any long-running code, so that the initial request "completes" as quickly as possible.

ASP.NET will serially process requests on a per-session basis unless sessions are configured as disabled or read only in web.config via the enableSessionState attribute on the pages element.
As this is a page setting, this will not affect MVC controllers and they will still be subject to serial request processing.
Curiously, even with sessions disabled or set to readonly, we can still read and write session data. It seems to only affect the session locking that causes serial request processing.
<system.web>
<pages enableSessionState="ReadOnly"/>
</system.web>
Pages can also have an enableSessionState property, though this is not relevant to MVC views.
<%# Page EnableSessionState="True" %>

With the release of ASP.MVC 3 you can now add an attribute to your controllers to mark the Session as readonly, which allows actions to be called concurrently from the same client.
Sessionless Controller Support:
Sessionless Controller is another great new feature in ASP.NET MVC 3. With Sessionless Controller you can easily control your session behavior for controllers. For example, you can make your HomeController's Session as Disabled or ReadOnly, allowing concurrent request execution for single user. For details see Concurrent Requests In ASP.NET MVC and HowTo: Sessionless Controller in MVC3 – what & and why?.
- from this DZone article.
By adding SessionState(SessionStateBehaviour.Disabled) to your controller, the runtime will allow you to invoke multiple actions concurrently from the same browser session.
Unfortunately I don't think there is a way to mark an action so as to only disable the session when that action is called, so if you have a controller that has some actions that require the session and others that do not, you will need to move the ones that do not into a separate controller.
In later versions of ASP MVC you can decorate individual controller classes with the SessionStateAttribute
[System.Web.Mvc.SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]
public class MyController : Controller
{
}

Since .NET Framework v3.0 released, you can use "SessionStateBehavior" enum with SessionStateAttribute:
[SessionState(System.Web.SessionState.SessionStateBehavior.ReadOnly)]
public class MyController : BaseController { }

Well Concurrent Request are more on browser dependent aswell if you fire suppose 10 concurrent request to an action Using AJax in Mozilla and same using IE 8 then you will find that Mozilla has style to fire one request wait for its response and then fire second and so on... for this is one by one basis whereas in IE * this fire about 6 concurrent request at a time to Server.
So Concurrent Request are also dependent on browser type.

I suggest using jQuery for your ajax needs with asp.net mvc, I have used it exclusively and it has been extremely easy.
As for tutorials I would look at this: http://docs.jquery.com/Ajax
There are tons of options to play with and I also suggest downloading firebug so you can watch requests launch from your page asynchronously and see if they fire and what they return etc.
Like the other guy side, AJAX request are asynchronous and don't get queued up and they all return independently when they finish, so if you watch in firebug it will be easy to see what is going on behind the scenes and before the debugger gets hit

Related

SessionSecurityTokenReceived called too many times

I have a Web Forms application which makes use of WIF and Claims based authorization. Im using Thinktecture IdentityServer v2.5 for my STS with my custom login page and custom authentication against database and then issuing the token.
Its all working fine at the moment and no issues, the only problem came when I was configuring Sliding Sessions as shown by Brock Allen in this post
http://brockallen.com/2013/02/17/sliding-sessions-in-wif-with-the-session-authentication-module-sam-and-thinktecture-identitymodel/
My problem is that the event mentioned in the post SessionSecurityTokenReceived is getting called too many times per page load. I just wanted to know what is the reason behind that and could this be a performance hit ?
I'm doing something similar and have come across the same issue. It is because the event is called for every single resource the page consumes (css, js, etc) that is also secured by the web application. In global.asax.cs, in the event, if you insert the line...
var requestContext = HttpContext.Current.Request.RequestContext.HttpContext.Request;
...and put a breakpoint on this line, you can observe this behavior by inspecting the value.

Durandal: intercept view loading to handle unauthorized requests (ASP.NET MVC server)

I've just started converting a Knockout-driven SPA to use Durandal. Due to server legacy, views are served through ASP.Net MVC endpoints that return an ActionResult. In the case of accessing a route that should not be available to the current user, or for example when the session has expired, the server will return JSON instead of HTML.
Durandal seems to make the assumption that HTML will always be returned from the specified view endpoint. Is there any way for me to hook into the process of loading a view so I can process the JSON that comes with an unauthorized request?
In the future the server will be updated to use the Web API. At that point, I will have to solve the same problem, but in that case I will have to handle different response codes.
Thanks in advance!
Here is what I think you may do,
Instead of letting the default view locator load the view for you, you can add a callback method getView method in your viewModel. In the callback method you can load the view (using text.js or jquery), then you have full control of what you want to do with the non-HTML responses (may be switch to a canned error view etc).
More info at Durandal Docs http://durandaljs.com/documentation/Interacting-with-the-DOM/

ASP.NET MVC hits outputcache for every action

We are running quite a large site build with ASP.NET MVC 3 and AppFabric as a distributed caching solution. We have implemented a custom OutputCacheAdapter to use our AppFabric cluster.
We are seeing that ASP.NET calls the OutputCacheProvider.Get() method for every action, even if that action is NOT decorated with a #OutputCacheAttribute.
That isn't much of a problem if you use the default outputcacheprovider but it is when you are running an outputcacheprovider that resides on seperate machines.
It is by design that the the output cache is checked first for a cached copy of the page. If there is a cached copy, it's returned and nothing further is executed. In particular, no controller and no controller action is derived, inspected or executed. This happens only if the page is not cached.
You will need to change your cache provider so that it can quickly determine if a page can potentially be cached. Only if it is a cachable page, then it should go and check the distributed cache. This check cannot based on the OutputCacheAttribute as they are not available during this part of the request processing. Instead, the quick check must be made with the URL, the cookies and other HTML header information.
You can use Donut Cache outputcache attribute which lets you to define a prefix for output cache keys. So in your custom provider just get/set the cache if cache key starts with your own prefix.

HttpSession without cookie

I have an application a the moment which for a particular set of reasons will be interacting oddly with the hosting server.
The application is to be accessed through a larger portal and can be encapsulated within the portal display, however it makes extensive use of AJAX requests which are not intercepted by the portal. These requests are made directly to the hosting server, however I am seeing a problem.
When the first ajax request is made (a little way into the application flow) the Ajax request is not carrying with it the JSessionId cookie (obviously as it's sending this to a different server than it received it from)
Is there a good grails way to find the session the AJAX call should be interacting with. I have tried setting grails.views.enable.jsessionid to true, but this only works if the browser is not accepting cookies.
Create a hidden form input value that has the jsessionid in it on the page you send back to the portal on the first request. Then read that form variable, and set the cookie in your javascript code that makes the AJAX request.
I'm guessing seeing that this already works, cross-site scripting isn't an issue? AJAX requests to domains other than that which the main page originated from will be blocked by the browser.
The most reliable way will be for you to set up your own "cookie" and pass that along with the requests.
It sounds like you are running into issues due to the portal and it's cookies and then having to continue that "session" onto a different server. Your application needs to simply handle it's own sessions itself in order to prevent getting stomped on by the "normal" cookies.
The idea is essentially to create a session token when the portal makes a request from to your application, and then the subsequent AJAX calls your application makes back to it's own server should include that token. You can then easily associate that token with the session you need to be using.
If you are looking to make it a bit more robust and handle it above the level of your application, you can leverage the fact that Grails is built on Spring MVC deep down and override the default session handler to pick up on whatever mechanism you decide to go with. I'm not sure of exactly how to do this with Grails, but I've done similar things on Spring MVC projects and it isn't too tough once you get your head wrapped around the various injection points of the framework.
It isn't ideal, since there is now a fair bit more complexity, but in theory, the benefits of the portal are outweighing the added complexity required for traditionally "handled" things like sessions and expiring them, etc.

In an ASP.NET MVC 3 application, how can I save the post data in the where their session times out

I have an ASP.NET MVC 3 application. The site involves people writing lengthy responses using a textarea in a web form. Occasionally, users are complaining that they are getting redirected to the log in form after they post their data. I am not sure exactly why they are getting logged out because the users do not typically provide enough information on their errors. I believe it is due either to a session time out or the application has been restarted for some reason. This is on a shared web hosting site and it does not have its own app pool.
In any case, regardless of the reason, I would like to capture that post data and save it to a db or text file. How can I get the post data and save it while the controller redirects the user to the login screen.
I know the long term plan would be to identify why the timeout is occurring. But for now I want to be able to grab the post data and recover it at a later time.
First, in order to avoid timeouts, I would recommend using client-side heartbeat solution (like http://plugins.jquery.com/project/Heartbeat)
Second, assuming that you are using forms authentication, in order to save posted data, when Forms Authorization Module is redirecting your users, you will need to intercept redirects in EndRequest HttpApplication event handler in Global.asax or your own module.
The way to intercept those requests is not that straightforward, since on "EndRequest" pipeline step you will see 302 HTTP status code (redirect instruction), not 401 (Unauthorized error). So you may check if request is not authenticated (HttpContext.User.Identity.IsAuthenticated) and request is redirected - in this case you may save what you see in the request.
Otherwise you would need to disable forms authentication and use some solution, which is closer to ASP.NET MVC.
one solution can be to put a javasscript timer which keeps on hitting the server after specified interval to keep session alive until u figure out the cause of session time out (only i its the session timeout problem)
If you want to stop the session from timing out, you can add a hidden iframe on the page. For example, create a new page called KeepSessionAlive and do this:
<meta http-equiv="refresh" content="600">
where content = seconds.
I don't know about MVC 3, but the way you can get and store the post values is to catch them before redirecting the user to the Login page.

Resources