使用asp.net core的最简单的Web服务器代码是什么?

问题描述 投票:0回答:4

我正在尝试学习asp.net core,但我发现这些示例对我来说太复杂了。即使对于模板创建的新项目,我也看到了依赖注入、MVC、实体框架。我只想使用 asp.net core 编写一个最简单的代码,并在网络浏览器上输出一些 hello world。

我所说的“最简单”,是指 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)
}

我喜欢这段代码的原因是我可以看到我应该从 net/http 模块开始,看看 HandleFunc 的方法会发生什么。 我讨厌当前的 ASP.NET Core 示例的原因是,我一次被这么多新的程序集和类淹没。

任何人都可以向我展示一个简单的示例,或者简单示例的链接,以便我可以一一学习 asp.net core 中的新概念吗?

asp.net-core
4个回答
7
投票

这是一个简单的 Web 服务器,具有一个功能,没有 IIS 依赖。

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");
            }
        }
    }
}

4
投票

尝试空模板:新建项目/ASP.NET Web 应用程序,从“ASP.NET 5 模板”部分选择“空”。它将创建一个最小的 Web 应用程序,对每个请求回答“Hello world”。代码全部在Startup.cs中:

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

如果您不使用完整的 IIS,则可以删除对

UseIISPlatformHandler()
的调用,并从 project.json 中摆脱对
Microsoft.AspNet.IISPlatformHandler
的依赖。 从那时起,您开始通过中间件添加静态文件、默认文件、mvc、实体框架等功能。


1
投票

这是我的建议:

  1. 控制台应用程序示例开始,它将教您新运行时 DNX 的基础知识
  2. 然后使用空网络应用程序继续工作。选择“空”而不是“Web 应用程序”以使其尽可能干净。
  3. 然后我将继续使用MVC。您可以忽略实体框架的内容。深入研究依赖注入,因为它是 asp.net core 工作原理的核心。

祝你好运!


0
投票

ASP.NET Core 具有最少的 API

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/{name}", (string name) => $"Hello {name}!");

app.Run();
© www.soinside.com 2019 - 2024. All rights reserved.