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

时间:2016-04-06 14:25:22

标签: asp.net-core

我正在尝试学习asp.net核心,但我发现这些例子对我来说太复杂了。即使对于模板创建的新项目,我也看到依赖注入,MVC,实体框架。我只想用asp.net核心编写一个最简单的代码,并在Web浏览器上输出一些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核心示例的原因是我一次被这么多新的程序集和类所淹没。

有没有人可以给我一个简单的例子,或者链接到简单的例子,以便我可以逐个学习asp.net核心中的新概念?

3 个答案:

答案 0 :(得分:2)

尝试使用Empty模板:New Project / 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)

这是一个简单的Web服务器,在一个没有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");
            }
        }
    }
}

答案 2 :(得分:0)

我建议您从控制台应用示例开始:https://docs.asp.net/en/latest/dnx/console.html(它将教您新运行时DNX的基础知识),然后使用空的Web应用https://docs.asp.net/en/latest/tutorials/your-first-aspnet-application.html(而不是“web应用程序”选择“空”以尽可能保持清洁。然后我将继续MVC:https://docs.asp.net/en/latest/tutorials/first-mvc-app/index.html

忽略实体框架的东西。深入了解依赖注入'因为它是asp.net核心工作原理的核心。祝你好运!