简体   繁体   中英

How can i build my class architecture for my asp.net web application

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?

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. Ie 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();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM