Asp.net Core Web API design best practice and consideration
In this article I will try to show some best practice when you start design your API.
- Before starting anything you should focus on Documentation.
So how you will documented your API endpoint, request, response?
There are lot’s of way to write good documentation automatically, one best options is swagger. So how will you use swagger? Just follow the below link
2. Return error details in the response body
So when you getting error. You should return details to your response. Not telling that you should throw technical error but business error details should be throw. That will help you to investigate the problem in future.
3. Response caching
Response caching reduces the number of requests a client or proxy makes to a web server. Response caching also reduces the amount of work the web server performs to generate a response. Response caching is controlled by headers that specify how you want client, proxy, and middleware to cache responses. You can follow the link.
4. Avoid blocking calls
Asp.net is designed to serve many request as possible simultaneously. So use asynchronous as much possible. Some of task shouldn’t doing like Task.Run,Task.wait or Task.Result
So if you want to investigate your application performance use https://github.com/Microsoft/perfview
5. Return exact http status code
what is this? As we sometimes send http 200 with error message. So you can then miss-leading as you got 200 but in response body you got error message.
So throw exact http code.
6. Environment based setting
In asp.net core you can notice that for every environment we can make the settings different like below.
You can add more settings here.
More you can learn from here how this will work for you.
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/environments?view=aspnetcore-2.1
7. Startup class and service configuration
You should aware to write anything on your startup class. Don’t make it so messy. Like if you register your automapper/ or dependency resolver, use different file also you can use extension class for every use of your service
public static class ServiceExtensions
{
public static void ConfigureCors(this IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
}
}
8. Clean Controller
We should maintain our controller clean. Business logic shouldn’t implement in controller. Also We should follow http verb like put,get,post,patch standard.
9. Handling Errors Globally
We should handle errors in startup. So any error we miss to handle can be caught here. Otherwise application can be stop.
public class CustomExceptionMiddleware
{
//constructor and service injection
public async Task Invoke(HttpContext httpContext)
{
try
{
await _next(httpContext);
}
catch (Exception ex)
{
_logger.LogError("Unhandled exception ...", ex);
await HandleExceptionAsync(httpContext, ex);
}
}
//additional methods
}//After that you should register your Middlewarepublic static IApplicationBuilder UseCustomExceptionMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<CustomExceptionMiddleware>();
}
and then use
app.UseCustomExceptionMiddleware();
10. Use Log
Not only in web api. You should write logs for every application you developed.
In asp.net core you can use LogforNet or even you can use Microsoft Logging framework. You can follow this guidline
11. Using DTOs to Return Results and to Accept Inputs
Sometimes we use same class for client input and response. It’s not so good practice. So we should avoid and maintain separate DTO’s for request, response.
12. Security and Using JWT
To authenticate your application I suggest you to use JWT . It will give you more flexible to secure your applications. You can check here how will you use JWT.
13. Routing
When we create routing we need to mention the route naming. We can use descriptive names for our actions, but for the routes/endpoints, we should use NOUNS and not VERBS.
14. Minimize exceptions
If possible reduce try and catch in normal code flow. It will slow your performance. Try to handle with logic
15. And Finally Hosting
So it will be more better if you host your asp.net core project to Linux. You can follow this instruction below.
A performance improves story