This is a personal template for backend project, to reduce duplicated startup thing.
- dotnet new webapi --use-controllers -o {ProjectName}.
- cd {ProjectName}.
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
for develop.- refer to MS_EF_packages, use
dotnet add package Microsoft.EntityFrameworkCore.{db_type}
(Sqlite,InMemory) to add ef. - More setup steps for EF, use the GUIDE
- dotnet dev-certs https --trust to use https.
- dotnet run --launch-profile https to start on https.
- execute vscode command .net: generate assets for build and debug to generate launch.json and task.json.
- if the dotnet version is 9 or above, the framework use openapi(~/openapi/v1.json) instead of the default swagger.
- Microsoft.AspNetCore.OpenApi will be install after project created by dotnet new webapi.
- openapi/v1.json only offers a json format document, if we want a UI format document just like swagger, MS now suggest to use Scalar.
- dotnet add package Scalar.AspNetCore to add Scalar to project.
- add app.MapScalarApiReference(); to program.cs.
- try access ~/scalar/v1 to get scalar for project documents.
- dotnet add package StyleCop.Analyzers.
- about Directory.Packages.props, some built-in packages will be added when executing dotnet new, we should add it to Directory.Packages.props first to keep the command going.
- global.json specifies the dotnet version dotnet cli command used, it was set to '9.0.100' as the latest till this submit.
- in the root folder, use dotnet new xunit -o {testProjectName} to create testproject.
- dotnet sln add {path to test.csproj} to add project to sln file, if visual studio is needed.
- cors problem: if API needs to be visit from an individually deployed website, add cors in Program.cs as follow or add specific headers, ips, or ports:
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(
b =>
{
b.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
...other codes
app.UseCors();