WebApiUtilities is a library that contains tools to facilitate the rapid development of RESTful ASP .Net Core 3.1 Web APIs utilising Entity Framework Core, Identity Server 4, JWT style authentication, Odata and Swagger.
- Make a new ASP .Net Core 3.1 Web API project and install the WebApiUtilities nuget package.
- For each domain model you wish to expose in the API you need to add the following classes
- Model which inherits from
Entity<TId>
ORAuditableEntity<TId>
- DTO which inherits from
Dto<TModel, TId>
and contains the same properties as TModel - A service interface which implemets
IRecordService<TModel, TId>
- A concrete service which inherits from
BaseRecordService<TDbContext, TModel, TId>
and inherits the service interface that you made previously. - A controller which inherits from
RecordController<TModel, TId, TDto>
- Model which inherits from
- Make a DbContext which inherits either
AuditingDbContext
ORIdentityDbContext
- In the ConfigureServices method of Startup.cs configure your DbContext, then add the following line. Also register the services that you made,
services.AddWebApiServices<TDbContext>(ApiTitle);
- In the Configure method of Startup.cs add IUserService to its signature, remove all of its contents except the use developer exception page if statment and add web api utitities. It should look like the following.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IUserService userService)
{
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
app.AddWebApiUtilities(GetEdmModel(), userService, {ApiTitle});
}
- In Startup.cs add the following method
IEdmModel GetEdmModel()
{
var odataBuilder = new ODataConventionModelBuilder();
//Duplicate this line for each entity
odataBuilder.EntitySet<TModel>(nameof(TModel));
return odataBuilder.GetEdmModel();
}
To add new endpoints for a model add a new method to the service interface then implement it in the concrete service. Then expose this methof in the record controller with the appropriate http verb and path.
Add a AppSettings section to appsettings.json then add the following keys and values to it.
JWTKey
- a string of characters which will be used to sign Json Web TokensSystemUserName
- the name of the system user for your api serviceSystemUserPassword
- the password of the system userSystemUserEmail
- the email of the system user
The system user name, password and email can be used to access the api via postman
- API endpoints are available at
/api/<TModel>/{id?}
- The Swagger UI is available at
/swagger
- Odata querying is available at
/api/<TModel>?$<query string>
- The identity server endpoint description is available at
/.well-known/openid-configuration
- A user registration endpoint is available at
/api/user/register
ITimeService an abstraction around DateTime which is by default bound to the Ioc container at startup and can be injected where needed and mocked in tests.
- Add entity configurations
- Add model validations
- Add RBAC authorization