分类 默认分类 下的文章

与标准默认WebApi区别:
缺少:

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();   

app.UserHttpsRedirection();
app.UseAuthorization();
app.MapControllers();


var builder = webApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello world!");
var app =webApplication .Create(args);
app.MapGet("/", () => "This is a GET");
app.MapPost("/",()=> "This is a POST");
app.MapPut("/", () => "This is a PUT");
app.MapDeleteC"/", () => "This is a DELETE");
app.Run();

这里的第一个参数可以进行路由约束,如app. MapGet("/posts/ {slug:regex(^[a-z0-9_ -]+5)}",(string slug) => $"Post
{slug}");

  • 自定类型

简单或复杂数据结构;

  • IActionResult

返回指定Http状态码;

  • Ok()
  • NotFound()

-ActionResult
可同时返回状态码及对象。
返回值为ActionResult< ItemClass>

举例:

API描述
GET /api/items获取所有item
GET /api/item/{id}获取制定项
POST /api/items添加新项
PUT /api/items/{id}更新现有项
DELETE /api/items/{id}删除现有项
不常用:
PATCH /api/items/{id}更新现有项部分内容

Controller下:

若方法为

public IActionResult method(){
  return View();
}

则会生成并返回 对应的View视图;

MVC 与 WebApi的区别:
mvc:
controller是实现Controller(继承自ContollerBase);
有添加ControllerWithViews 服务;
有Route;
能够使用Razor引擎(Cshtml)
WebApi:
Controller 继承 ControllerBase;
只能使用普通web调用接口(ajax,axios,fetch);
有swagger;