Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what's the simplest web server code using asp.net core?

Tags:

asp.net-core

I'm trying to learn asp.net core, but I found the examples are way too much complicated for me. Even for the new project created by templates, I see dependency injection, MVC, entity framework. I just want to write a simplest code using asp.net core and just output some hello world on web browser.

By 'simplest', I mean something like this in golang:

package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

The reason I like the code is that I can see that I should begin with net/http module and see what happens by the method of HandleFunc. The reason I hate current asp.net core examples is that I'm overwhelmed by so much new assemblies and classes at one time.

Could anyone show me a simple example, or a link to at simple example so that I can learn new concepts in asp.net core one by one?

like image 640
Felix Avatar asked Dec 18 '22 18:12

Felix


2 Answers

Here is a simple webserver in one function with no IIS deps.

using System;
using System.IO;
using System.Net;
using System.Threading;

namespace SimpleWebServer
{
    class Program
    {
        /*
        okok, like a good oo citizen, this should be a nice class, but for
        the example we put the entire server code in a single function
         */
        static void Main(string[] args)
        {
            var shouldExit = false;
            using (var shouldExitWaitHandle = new ManualResetEvent(shouldExit))
            using (var listener = new HttpListener())
            {
                Console.CancelKeyPress += (
                    object sender,
                    ConsoleCancelEventArgs e
                ) =>
                {
                    e.Cancel = true;
                    /*
                    this here will eventually result in a graceful exit
                    of the program
                     */
                    shouldExit = true;
                    shouldExitWaitHandle.Set();
                };

                listener.Prefixes.Add("http://*:8080/");

                listener.Start();
                Console.WriteLine("Server listening at port 8080");

                /*
                This is the loop where everything happens, we loop until an
                exit is requested
                 */
                while (!shouldExit)
                {
                    /*
                    Every request to the http server will result in a new
                    HttpContext
                     */
                    var contextAsyncResult = listener.BeginGetContext(
                        (IAsyncResult asyncResult) =>
                        {
                            var context = listener.EndGetContext(asyncResult);
                            Console.WriteLine(context.Request.RawUrl);

                            /*
                            Use s StreamWriter to write text to the response
                            stream
                             */
                            using (var writer =
                                new StreamWriter(context.Response.OutputStream)
                            )
                            {
                                writer.WriteLine("hello");
                            }

                        },
                        null
                    );

                    /*
                    Wait for the program to exit or for a new request 
                     */
                    WaitHandle.WaitAny(new WaitHandle[]{
                        contextAsyncResult.AsyncWaitHandle,
                        shouldExitWaitHandle
                    });
                }

                listener.Stop();
                Console.WriteLine("Server stopped");
            }
        }
    }
}
like image 128
Elmer Avatar answered Jan 09 '23 00:01

Elmer


Try the Empty template: New Project/ASP.NET Web application, choose 'Empty' from 'ASP.NET 5 Templates' section. It will create a minimal web application that answers 'Hello world' to every request. The code is all in Startup.cs:

public void Configure(IApplicationBuilder app)
{
    app.UseIISPlatformHandler();
    app.Run(async (context) =>
        {
            await context.Response.WriteAsync("Hello World!");
        });
}

If you don't use the full IIS, you can delete the call to UseIISPlatformHandler() and get rid of the dependency on Microsoft.AspNet.IISPlatformHandler from project.json. From that, you start adding functionality like static files, default files, mvc, Entity Framework, etc. via Middleware.

like image 45
Ernesto Cullen Avatar answered Jan 09 '23 00:01

Ernesto Cullen