Home > Software design >  Creating HTTP Server with API and listener for all API calls
Creating HTTP Server with API and listener for all API calls

Time:06-22

I'm facing with problem about creating HTTP server which has API on his side and also is able to listen all calls and log it. I want to create something like: Hub - server responsible for handle my window services which will registered, also communication logging between hub and nodes. Nodes - window services which working as Client, which executing some tasks and using Hub API are able to logging information about that.

I dont know it is possible to create HTTP server which include API and HTTPListener. I tried like that, but this wont work.

Example:

static void Main(string[] args)
    {
        var httpServer = new HttpServer();

        httpServer.Start(); //Listener using address - http://localhost:8080 the same as SelfHostServer

        Console.WriteLine("Starting HTTP listener...");

        var config = new HttpSelfHostConfiguration("http://localhost:8080/");

        config.Routes.MapHttpRoute(
            "API Default", 
            "api/{controller}/{id}",
            new { id = RouteParameter.Optional });

        using (HttpSelfHostServer server = new HttpSelfHostServer(config))
        {
            server.OpenAsync().Wait();
            Console.WriteLine("Press Enter to quit.");
            Console.ReadLine();
        }

        while (Program._keepRunning) { }

        httpServer.Stop();

        Console.WriteLine("Exiting gracefully...");
    }

Im not sure Im going good way, maybe I should create a separate server to listen and a separate selfhost server for the API? Can someone explain what should I do for achive this? Thanks

EDIT

I want to avoid this: enter image description here

CodePudding user response:

I can recommend you this simple working server template (However it is better to use frameworks like asp net core instead of your approach):

public class Program
{
    public static HttpListener listener;
    public static string url = "http://localhost:8000/";
    public static int pageViews = 0;
    public static int requestCount = 0;
    public static string pageData =
        "<!DOCTYPE>"  
        "<html>"  
        "  <head>"  
        "    <title>HttpListener Example</title>"  
        "  </head>"  
        "  <body>"  
        "    <p>Page Views: {0}</p>"  
        "    <form method=\"post\" action=\"shutdown\">"  
        "      <input type=\"submit\" value=\"Shutdown\" {1}>"  
        "    </form>"  
        "  </body>"  
        "</html>";


    public static async Task HandleIncomingConnections()
    {
        bool runServer = true;

        while (runServer)
        {
            HttpListenerContext ctx = await listener.GetContextAsync();

            HttpListenerRequest req = ctx.Request;
            HttpListenerResponse resp = ctx.Response;

            // Print out some info about the request
            Console.WriteLine("Request #: {0}",   requestCount);
            Console.WriteLine(req.Url.ToString());
            Console.WriteLine(req.HttpMethod);
            Console.WriteLine(req.UserHostName);
            Console.WriteLine(req.UserAgent);
            Console.WriteLine();

            if ((req.HttpMethod == "POST") && (req.Url.AbsolutePath == "/shutdown"))
            {
                Console.WriteLine("Shutdown requested");
                runServer = false;
            }

            // Write the response info
            var disableSubmit = !runServer ? "disabled" : "";
            var data = Encoding.UTF8.GetBytes(String.Format(pageData, pageViews, disableSubmit));
            resp.ContentType = "text/html";
            resp.ContentEncoding = Encoding.UTF8;
            resp.ContentLength64 = data.LongLength;

            await resp.OutputStream.WriteAsync(data, 0, data.Length);
            resp.Close();
        }
    }


    public static void Main(string[] args)
    {
        listener = new HttpListener();
        listener.Prefixes.Add(url);
        listener.Start();
        Console.WriteLine("Listening for connections on {0}", url);

        var listenTask = HandleIncomingConnections();
        listenTask.GetAwaiter().GetResult();

        listener.Close();
    }


}

CodePudding user response:

I was looking for middleware - https://docs.microsoft.com/pl-pl/aspnet/core/fundamentals/middleware/?view=aspnetcore-6.0

Selfthost API server and HttpListener server was not needed. All my web api calls will be catch and I can log all communications:

app.Use(async (context) => func with logic for logging });
  • Related