ASYNC REQUESTS IN ASP.NET

ASYNC REQUEST VS SYNC REQUEST ON IIS 7.5

Creating an Asynchronous HTTP Handler

http://msdn.microsoft.com/en-us/library/ms227433(v=vs.100).aspx

. Asynchronous HTTP HANDLERS enable you to start an external process (such as a method call to a remote server) while the handler continues processing. The handler can continue without waiting for the external process to finish.

During processing of an asynchronous HTTP handler, ASP.NET puts the thread that would ordinarily be used for the external process back into the thread pool until the handler receives a callback from the external process. This can prevent thread blocking and improve performance, because only a limited number of threads can be executing at the same time. If many users request synchronous HTTP handlers that rely on external processes, the operating system can quickly run out of threads because many threads are blocked and waiting for an external process.

http://www.hanselman.com/blog/TheMagicOfUsingAsynchronousMethodsInASPNET45PlusAnImportantGotcha.aspx

AN ASYNC REQUEST DOES NOT WAIT FOR A RESPONSE (it simply registers a callback and moves on)

AN ASYNC RESOURCE (SERVICE) DOES NOT BLOCK THE THREAD ITS EXECUTING ON (it simply let go of the thread when a blocking operation is to be performed and sits pretty awaiting the result)

 

An asynchronous request takes the same amount of time to process as a synchronous request. However, during an asynchronous call, the server is not blocked from responding to other requests while it waits for the first request to complete. Therefore, asynchronous requests prevent request queuing when there are many requests that invoke long-running operations http://msdn.microsoft.com/en-us/library/ee728598(v=vs.100).aspx

Make siteminder call from c# code

Make siteminder call from c# code

how to do siteminder authentication when consuming a webAPI using c# (Eg. WinForm  Application)

 

Make a call to get the sm cookies

 

string requestData = request;

httpRequestToConnect = WebRequest.Create(dUrl) as HttpWebRequest;

httpRequestToConnect.Method = “GET”;

if (aConfig.HttpRequestTimeOut != 0)

httpRequestToConnect.Timeout = aConfig.HttpRequestTimeOut;

httpRequestToConnect.Credentials = CredentialCache.DefaultCredentials;

setCookies(httpRequestToConnect, dUri, dBaseUri);

httpRequestToConnect.BeginGetResponse(new AsyncCallback(ResponseFromD), httpRequestToConnect);

 

 

————

private void setCookies(HttpWebRequest webRequest, Uri dUri, Uri dBaseUri)

{

CookieContainer cookieContainer = null;

if (cookieContainer == null)

{

lock (typeof(CookieContainer))

{

CookieContainer tempCookieContainer = new CookieContainer();

try

{

if (dBaseUri != null && !dBaseUri.Equals(string.Empty))

{

string cookie = System.Windows.Application.GetCookie(dBaseUri) + “; domain=.a.b; path=/”;

cookie = cookie.Replace(‘;’, ‘,’);

tempCookieContainer.SetCookies(dUri, cookie);

}

}

cookieContainer = tempCookieContainer;

}

}

webRequest.CookieContainer = cookieContainer;

}

 

 

 

 

CORS in WebAPI 2.0

CORS in WebAPI

Install-PackageMicrosoft.AspNet.WebApi.Cors-pre-projectWebServic

 

 

http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

http://msdn.microsoft.com/en-us/magazine/dn532203.aspx

 

The thing Is that I can always change my browser call to a server call, but the issue is that all calls in my web Farm are siteminder authenticated and so I’m not sure: how to do siteminder authentication when consuming a webAPI using c#

Enabling at:

  1. Class Level: [EnableCors(“*”, “*”, “*”)]
  2. Action Level:

[EnableCors(“*”,       // Origin

“Accept, Origin, Content-Type”, // Request headers

“POST”,                         // HTTP methods

PreflightMaxAge = 600             // Preflight cache duration

)]

  1. [EnableCors(origins: “http://example.com”, headers: “*”, methods: “*”)]  //http://enable-cors.org/server_aspnet.html

 

Simple Request

$http.get(“http://a.com:12140/b/c”,{ withCredentials: true}).success(function () {

alert(‘success’);

}).error(function () {

alert(‘fail’);

})();

 

ENABLLING CORS WITHOUT THE CORS NUGET PACKAGE

http://www.codeproject.com/Articles/617892/Using-CORS-in-ASP-NET-WebAPI-Without-Being-a-Rocke

 

Add in web.config:

<system.webServer>

<httpProtocol>

<customHeaders>

<!– Adding the following custom HttpHeader will help prevent CORS from stopping the Request–>

<add name=”Access-Control-Allow-Origin” value=”http://as.ms.com:12150 http://as.ms.com:12150&#8243; /> // NOTE THAT MULTIPLE VALUES ARE NOT ALLOWED…

<add name=”Access-Control-Allow-Credentials” value=”true” />

</customHeaders>

</httpProtocol>

</system.webServer>

 

ECHOING THE ORIGIN HEADER :

http://stackoverflow.com/questions/6290053/setting-access-control-allow-origin-in-asp-net-mvc-simplest-possible-method

http://stackoverflow.com/questions/1653308/access-control-allow-origin-multiple-origin-domains/1850482#1850482

 

publicclassAllowCrossSiteJsonAttribute : ActionFilterAttribute

{

publicoverridevoidOnActionExecuting(ActionExecutingContext filterContext)

{

// We’d normally just use “*” for the allow-origin header,

// but Chrome (and perhaps others) won’t allow you to use authentication if

// the header is set to “*”.

// TODO: Check elsewhere to see if the origin is actually on the list of trusted domains.

var ctx = filterContext.RequestContext.HttpContext;

var origin = ctx.Request.Headers[“Origin”];

var allowOrigin = !string.IsNullOrWhiteSpace(origin) ? origin : “*”;

  1. Response.AddHeader(“Access-Control-Allow-Origin”, allowOrigin);
  2. Response.AddHeader(“Access-Control-Allow-Headers”, “*”);
  3. Response.AddHeader(“Access-Control-Allow-Credentials”, “true”);

base.OnActionExecuting(filterContext);

}

}

 

Error handling in WebAPI

 

Currently I have multiple webAPI Controllers and each is returning a different object. I need a consistent way of returning the errors from all in case of exception etc.

For this I did this:

throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, “Exception occurred in host : ” + Environment.MachineName + “Error: “+ ex.Message + “/r/n” + “Stack Trace: ” + ex.StackTrace));

 

In all get and post requests.

The reason I’m sending the host name is coz this is a web farm and so the client is making a req. to the farm url. For debugging on the server side it’s important that we know the exact server that’s throwing the error for easy debugging.

Additionally In the post requests for success I am sending:

return Request.CreateResponse(HttpStatusCode.OK);

 

Note that the response type for the POST Operations is public HttpResponseMessage Post(JObject AgentConfig)

 

Another way of passing custom fields in the error scenario to a web client is to always return a JObject and  this way for success return the expected response JSON and in case of error, return JSON containing all details like this:

{

“Error message”: “ ”,

“Details” : “ ”,

“Stack Trace”: “ ”

}