ASP.NET Core中的Post请求与响应

1.HttpContext

后端:

app.UseHttpLogging();
app.MapPost("/Test", (HttpContext httpContext) =>
{
    string para = httpContext.Request.Form["para"];
    return httpContext.Response.WriteAsync($"para={para}");
});

前端:

wx.request({
    url: 'http://localhost:5140/test',
    method: 'POST',
    header: { "Content-Type": "application/x-www-form-urlencoded" },
    data: { para: "today is Tuesday" },
    success: res => console.log(res.data)
});

header: { "Content-Type": "application/x-www-form-urlencoded" }为必须项。

结果:

para=today is Tuesday

2.实体类

后端:

using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext(options => options.UseSqlServer(builder.Configuration.GetConnectionString("XunceWx")));
var app = builder.Build();

app.MapPost("/Test", (Customer customer) =>
{
    return Results.Ok($"name:{customer.Name},tel:{customer.Tel}");
});

app.Run();

class Customer
{
    [Key]
    public long Id { get; set; }
    public string? Name { get; set; }
    public string? Tel { get; set; }
}
#nullable disable
class CustomerDb : DbContext
{
    public CustomerDb(DbContextOptions options) : base(options) { }
    public DbSet Customer { get; set; }
}

前端:

wx.request({
    url: 'http://localhost:5013/test',
    method: 'POST',
    data: JSON.stringify({ id: 17, name: 'fakename', tel: 'faketel' }),
    header: { "Content-Type": "application/json" },
    success: res => console.log(res.data)
});

header: { "Content-Type": "application/json" }为必须项。

结果:

name:fakename,tel:faketel

你可能感兴趣的:(C#,.Net,6,asp.net,core,http)