Saturday, 6 December 2014

How to get an HttpContextBase object from HttpContext.Current?


I was helping a friend to implement OAuth login for Facebook. He was using DotNetOpenAuth extensions for ASP.NET, downloaded as NuGet package.
The code look like this

Uri ui=new Uri("~/Login.aspx");

DotNetOpenAuth.AspNet.Clients.FacebookClient fbClient = new FacebookClient("***", "***********");
fbClient.RequestAuthentication(context, ui);

The first parameter of the RequestAuthentication it is asking for httpContextBase object. If you try to pass HttpContext.Current, it will throw an error. Like name suggests HttpContext.Current does not inherit from HttpContextBaseHttpContextBase was introduced to abstract away direct access to HttpContext.

The solution is simply instantiate an HttpContextWrapper object. HttpContextWrapper works as an adapter between two classes of different interfaces. Its primary use is to adapt the context to be the context base. So this wraps access to members of HttpContext.

// HttpContextBase from HttpContext.Current
var httpContextBase = new HttpContextWrapper(HttpContext.Current);
fbClient.RequestAuthentication(httpContextBase , ui);



/Adnan

0 comments :

Post a comment