WebApiToolkit
v1.6.0
C#和AspNet构建REST API 。 
CRUD的REST API Controller仅包含20行代码(〜10是导入)GET方法具有内置的分页支持;GET方法具有内置的排序和滤波参数过滤;Create , Update和Delete )支持批量操作&&接口级别IModelManager接口);良好的内置实体Framework支持(请参阅EfModelManager类)。请参阅具有2个Web API项目的WeatherControl应用:Wissance.WeatherControl.WebApi使用EntityFramework ;Wissance.WeatherControl.WebApi.V2使用EdgeDb 。关键概念:
Controller是一个将HTTP-requests为REST Resource类。REST Resource等于Entity class / Database TableREST Resource上的每个操作都以DTO为输出产生JSON 。我们假设仅使用一个与所有REST方法一起使用一个DTO类。DTO课程:
OperationResultDto代表操作的结果,该操作会更改数据库中的数据;PagedDataDto表示相同对象的一部分(任何类型); Controllers类 - 抽象类
BasicReadController )包含2种方法:GET /api/[controller]/?[page={page}&size={size}&sort={sort}&order={order}]现在,我们也有可能将任何数量的查询参数发送到任何数量的查询参数,您只需将func通过EfModelManager或以efmodelmanager或自己的方式进行审理PagedDataDto<T>或者像efmodelmmanager或自己的方式一样。我们还将Sort(列名)&&订单( asc或desc )传递给Manager类, EfModelManager允许通过任何列进行排序。Swagger Info以显示查询参数使用情况!!!1.6.0开始,可以看到所有参数, Swagger使用它们。GET /api/[controller]/{id}通过id获取一个对象CRUD Controller( BasicCrudController )=基本读取控制器( BasicReadController ) + Create , Update和Delete操作:POST /api/[controller] - 用于新对象创建PUT /api/[controller]/{id} - 用于ID编辑对象DELETE /api/[controller]/{id} - delete对象通过IDCRUD (一次通过多个对象进行操作),基类BasicBulkCrudController =基本读取控制器( BasicReadController ) + BulkCreate , BulkUpdate和BulkDelete操作:POST /api/bulk/[controller] - 用于新对象创建PUT /api/bulk/[controller] - 用于通过请求正文传递的对象DELETE /api/bulk/[controller]/{idList} - 用于通过ID删除多个对象。控制器类预计所有操作将使用管理员类执行(每个控制器都必须拥有自己的管理器)
经理类 - 实现应用程序业务逻辑的课程
IModelManager描述基本操作的接口EfModelManager是包含Get和Delete操作的实现的抽象类EfSoftRemovableModelManager是抽象类,包含具有软可移动模型的Get和Delete操作的实现( IsDeleted = true Menage模型)较快散装与非欺凌的示例: 
Elapsed time in Non-Bulk REST API with EF is 0.9759984016418457 secs.
Elapsed time in Bulk API with EF is 0.004002094268798828 secs.
结果,我们的API速度将近250 x 。
只有一个要求:所有用于控制器和管理人员使用的持久存储的实体类都必须从Wissance.WebApiToolkit.Data.Entity实现IModelIdentifiable<T>例使用一下。如果应与EntityFramework一起使用此工具包,则应从EfModelManager得出资源管理器,其内置方法适用于:
get many物品by id get one项目by id delete项目第6节中提到了完整示例(见下文)。但是,如果您开始构建新的REST Resource API则应执行以下操作:
model ( entity )类,以实现IT表示IModelIdentifiable<T>和DTO类(用于软删除还添加IModelSoftRemovable ),即: public class BookEntity : IModelIdentifiable < int >
{
public int Id { get ; set ; }
public string Title { get ; set ; }
public string Authors { get ; set ; } // for simplicity
public DateTimeOffset Created { get ; set ; }
public DateTimeOffset Updated { get ; set ; }
}
public class BookDto
{
public int Id { get ; set ; }
public string Title { get ; set ; }
public string Authors { get ; set ; }
}Model转换为DTO IE的出厂功能(即静态类的静态函数): public static class BookFactory
{
public static BookDto Create ( BookEntity entity )
{
return new BookDto
{
Id = entity . Id ,
Title = entity . Title ,
Authors = entity . Authors ;
} ;
}
}IModelContext界面,使您可以BookEntity作为DbSet及其实现类,该类也来自DbContext ( EF摘要类): public interface IModelContext
{
DbSet < BookEntity > Books { get ; set ; }
}
public MoidelContext : DbContext < ModelContext > , IModelContext
{
// todo: not mrntioned here constructor, entity mapping and so on
public DbSet < BookEntity > Books { get ; set ; }
}ModelContext作为DbContext通过DI参见启动类Controller类和经理课程对,即在这里考虑完整的CRUD [ ApiController ]
public class BookController : BasicCrudController < BookDto , BookEntity , int , EmptyAdditionalFilters >
{
public BookController ( BookManager manager )
{
Manager = manager ; // this is for basic operations
_manager = manager ; // this for extended operations
}
private BookManager _manager ;
}
public class BookManager : EfModelManager < BookEntity , BookDto , int , EmptyAdditionalFilters >
{
public BookManager ( ModelContext modelContext , ILoggerFactory loggerFactory ) : base ( modelContext , BookFactory . Create , loggerFactory )
{
_modelContext = modelContext ;
}
public override async Task < OperationResultDto < StationDto > > CreateAsync ( StationDto data )
{
// todo: implement
}
public override async Task < OperationResultDto < StationDto > > UpdateAsync ( int id , StationDto data )
{
// todo: implement
}
private readonly ModelContext _modelContext ;
}上面示例中的最后一个通用参数 - EmptyAdditionalFilters是一个包含其他参数以搜索的类,只需指定一个实现IReadFilterable的新类,即:
public class BooksFilterable : IReadFilterable
{
public IDictionary < string , string > SelectFilters ( )
{
IDictionary < string , string > additionalFilters = new Dictionary < string , string > ( ) ;
if ( ! string . IsNullOrEmpty ( Title ) )
{
additionalFilters . Add ( FilterParamsNames . TitleParameter , Title ) ;
}
if ( Authors != null && Authors . Length > 0 )
{
additionalFilters . Add ( FilterParamsNames . AuthorsParameter , string . Join ( "," , Authors ) ) ;
}
return additionalFilters ;
}
[ FromQuery ( Name = "title" ) ] public string Title { get ; set ; }
[ FromQuery ( Name = "author" ) ] public string [ ] Authors { get ; set ; }
}您可以在这里找到Nuget-ackage
[ ApiController ]
public class StationController : BasicCrudController < StationDto , StationEntity , int , EmptyAdditionalFilters >
{
public StationController ( StationManager manager )
{
Manager = manager ; // this is for basic operations
_manager = manager ; // this for extended operations
}
private StationManager _manager ;
} public class StationManager : EfModelManager < StationEntity , StationDto , int >
{
public StationManager ( ModelContext modelContext , ILoggerFactory loggerFactory ) : base ( modelContext , StationFactory . Create , loggerFactory )
{
_modelContext = modelContext ;
}
public override async Task < OperationResultDto < StationDto > > CreateAsync ( StationDto data )
{
try
{
StationEntity entity = StationFactory . Create ( data ) ;
await _modelContext . Stations . AddAsync ( entity ) ;
int result = await _modelContext . SaveChangesAsync ( ) ;
if ( result >= 0 )
{
return new OperationResultDto < StationDto > ( true , ( int ) HttpStatusCode . Created , null , StationFactory . Create ( entity ) ) ;
}
return new OperationResultDto < StationDto > ( false , ( int ) HttpStatusCode . InternalServerError , "An unknown error occurred during station creation" , null ) ;
}
catch ( Exception e )
{
return new OperationResultDto < StationDto > ( false , ( int ) HttpStatusCode . InternalServerError , $ "An error occurred during station creation: { e . Message } " , null ) ;
}
}
public override async Task < OperationResultDto < StationDto > > UpdateAsync ( int id , StationDto data )
{
try
{
StationEntity entity = StationFactory . Create ( data ) ;
StationEntity existingEntity = await _modelContext . Stations . FirstOrDefaultAsync ( s => s . Id == id ) ;
if ( existingEntity == null )
{
return new OperationResultDto < StationDto > ( false , ( int ) HttpStatusCode . NotFound , $ "Station with id: { id } does not exists" , null ) ;
}
// Copy only name, description and positions, create measurements if necessary from MeasurementsManager
existingEntity . Name = entity . Name ;
existingEntity . Description = existingEntity . Description ;
existingEntity . Latitude = existingEntity . Latitude ;
existingEntity . Longitude = existingEntity . Longitude ;
int result = await _modelContext . SaveChangesAsync ( ) ;
if ( result >= 0 )
{
return new OperationResultDto < StationDto > ( true , ( int ) HttpStatusCode . OK , null , StationFactory . Create ( entity ) ) ;
}
return new OperationResultDto < StationDto > ( false , ( int ) HttpStatusCode . InternalServerError , "An unknown error occurred during station update" , null ) ;
}
catch ( Exception e )
{
return new OperationResultDto < StationDto > ( false , ( int ) HttpStatusCode . InternalServerError , $ "An error occurred during station update: { e . Message } " , null ) ;
}
}
private readonly ModelContext _modelContext ;
}只有2个非常简单的类^^使用WebApitoolKit
考虑我们想将方法搜索添加到我们的控制器:
[ HttpGet ]
[ Route ( "api/[controller]/search" ) ]
public async Task < PagedDataDto < BookDto > > > SearchAsync ( [ FromQuery ] string query , [ FromQuery ] int page , [ FromQuery ] int size )
{
OperationResultDto < Tuple < IList < BookDto > , long > > result = await Manager . GetAsync ( page , size , query ) ;
if ( result == null )
{
HttpContext . Response . StatusCode = ( int ) HttpStatusCode . InternalServerError ;
}
HttpContext . Response . StatusCode = result . Status ;
return new PagedDataDto < TRes > ( pageNumber , result . Data . Item2 , GetTotalPages ( result . Data . Item2 , pageSize ) , result . Data . Item1 ) ;
} 我们还有其他项目可以通过Keycloak OpenId-Connect保护API 。将IHttpContextAccessor传递到Manager类,然后检查以下内容: ClaimsPrincipal principal = _httpContext.HttpContext.User;
您可以看到我们有关工具包使用的文章: