【Asp.Net.Core】【第一个程序】

207 阅读2分钟

使用Visual Studio 创建第一个Web应用

使用模板,打开一个.net.core的空项目,在Program.cs中的代码如下:

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

app.MapGet("/", () => "Hello World!");

app.Run();

Spring 初始化项目很类似。

Kestrel 和 其他 Servers

image.png

在我们日常开发中,我们使用Kestrel作为我们的Web服务器,在正式项目中,一般需要使用到反向代理服务器做到负载均衡,URL重写,认证等操作。 我们可以使用 IIS Express 模拟 一个反向代理服务器,

image.png

launchSettings.json 配置文件

通常情况下,一般会有两个 Profiles,在这里,我们仅使用kestrel,暂时不需要使用到负载均衡,身份认证等操作。

//iis更多的配置项
"iisSettings": {
  "windowsAuthentication": false,
  "anonymousAuthentication": true,
  "iisExpress": {
    "applicationUrl": "http://localhost:24971",
    "sslPort": 0
  }
},
"profiles": {
 //名字 "myFirstApp": { 
    "commandName": "Project",    //使用kestrel only
    "dotnetRunMessages": true,    //可以使用命令行
    "launchBrowser": true,         //自动打开页面
    "applicationUrl": "http://localhost:5142",    //URL
    "environmentVariables": {
      "ASPNETCORE_ENVIRONMENT": "Development"   //全局变量的使用范围
    }

  },
  //如果想要使用IIS Express  在运行键里有 IIS Express
  "IIS Express": {
    "commandName": "IISExpress",
    "launchBrowser": true,
    "environmentVariables": {
      "ASPNETCORE_ENVIRONMENT": "Development"
    }
  }
}

HTTP简介

image.png

打开任意一个页面,打开开发者选项,就可以看到发送的HTTP请求已经HTTP响应。

image.png

HTTP响应:

image.png

image.png

image.png

如何在代码中发送不同的状态码?

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

//app.MapGet("/", () => "Hello World!");
app.Run(async (HttpContext context) =>
{
    context.Response.StatusCode = 400;
    await context.Response.WriteAsync("Hello");
    await context.Response.WriteAsync("World");
});
app.Run();

image.png

image.png 代码里设置响应头:

app.Run(async (HttpContext context) =>
{
    context.Response.Headers["Content-Type"] = "text/html";

    await context.Response.WriteAsync("<h1>Hello<h1>");
    await context.Response.WriteAsync("<h2>World<h2>");
});
app.Run();

Http请求

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

//app.MapGet("/", () => "Hello World!");
app.Run(async (HttpContext context) =>
{
    
    string path = context.Request.Path;
    string method = context.Request.Method;
    context.Response.Headers["Content-Type"] = "text/html";
    await context.Response.WriteAsync($"<p>{path}<p>");
    await context.Response.WriteAsync($"<p>{method}<p>");
    
});
app.Run();

image.png

如何获取请求头中的请求参数?

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

//app.MapGet("/", () => "Hello World!");
app.Run(async (HttpContext context) =>
{
    context.Response.Headers["content-type"] = "text/html";
    if (context.Request.Method == "GET")
    {
        if(context.Request.Query.ContainsKey("id"))
        {
            string id = context.Request.Query["id"];
            await context.Response.WriteAsync($"<p>{id}<p>");
        }
    }
  
    
});
app.Run(); 

image.png

image.png

代码如何获得请求头中的信息?

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

//app.MapGet("/", () => "Hello World!");
app.Run(async (HttpContext context) =>
{
    context.Response.Headers["Content-type"] = "text/html";
    if (context.Request.Headers.ContainsKey("User-Agent"))
    {
         string userAgent = context.Request.Headers["User-Agent"];
         await context.Response.WriteAsync($"<p>{userAgent}<p>");
    }
  
    
});
app.Run();

image.png

如果使用代码获取请求体中的数据?

using Microsoft.Extensions.Primitives;
using System.IO;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

//app.MapGet("/", () => "Hello World!");
app.Run(async (HttpContext context) =>
{
    StreamReader reader = new StreamReader(
   context.Request.Body);
    string body = await reader.ReadToEndAsync();
    //stringValues 可出现重复的key,不同的value
   Dictionary<string,StringValues> queryDict = 
    Microsoft.AspNetCore.WebUtilities.QueryHelpers.ParseQuery(body);
    if(queryDict.ContainsKey("firstName"))
    {
        string firstName = queryDict["firstName"][0];    //可能有多个firstName键,只要第一个
        await context.Response.WriteAsync(firstName);
    }
});
app.Run();

在实际的项目中,我们不会使用如此原始的方式获取请求体或者响应体中的数据。