我正在尝试学习 asp.net 核心,但我发现这些示例对我来说太复杂了。即使对于由模板创建的新项目,我也看到了依赖注入(inject)、MVC、 Entity Framework 。我只想使用 asp.net core 编写一个最简单的代码,然后在 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 core中的新概念?
最佳答案
这是一个没有 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");
}
}
}
}
关于asp.net-core - 使用 asp.net 核心的最简单的 Web 服务器代码是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36454074/