views:

62

answers:

2

I'm building a web application using .net 2010, c#. I want to create several projects in one solution.

  1. A asp.net web application

  2. A class library to hold normal business logic.

  3. A class library to hold business logic to call a third party API.

When i call third party API, I need to login first, and third party API will return a session for me to communicate until I logout. What I want is to remain the same login session in asp.net web application. Which means when user logged in from web form, the program will login third party API and grab a session for that user; another user logged in from web form, the program will login third party API and grab another session for that user. whenever the user make some calls to the business logic layer, the method in business logic layer should be able to know which session from third party API it is using.

Also, I might want to reuse the 2 class library for a WPF app or a console app later.

How can I implement it?

+1  A: 

Just save the session information of the 3rd party API acquired from the login within the Session object of your ASP.NET application and re-use it for subsequent requests to the API. I.e. assuming the 3rd party is providing a session cookie with the name .ASPXAUTH you could do the following:

        api.CookieContainer = new System.Net.CookieContainer();
        api.Login(user_name, password);
        Session["APIAuthenticationCookie"] = api.CookieContainer.GetCookies(new Uri(api.Url))[".ASPXAUTH"];


    //later request: reuse session cookie before using API
    api.CookieContainer = new CookieContainer(); 
    Cookie sessionCookie = (Cookie)Session["APIAuthenticationCookie"];
    if (sessionCookie != null)
        api.CookieContainer.Add(sessionCookie);
    api.RandomRequest();
BrokenGlass
A: 

If you might reuse the class libraries, and if one of those libraries is meant to abstract the access to the third-party API, then you should have a class in that library which is the entry point for the API. It might include all of the methods of that API, or it might explicitly represent a "session" with that API.

This class should call the "login" method of the API as needed, and should hold a copy of the session key that the API returns.

In your ASP.NET application, you should keep an instance of this class in ASP.NET Session state. That way, there will be one per user. In a Console or WPF application, just keep one instance around as a class member, perhaps as a static member.

John Saunders