Skip to content
Sergey Tregub edited this page Jan 17, 2019 · 17 revisions

Welcome to the ASP.Net Core RESTful Service wiki!

Cross-Origin Resource Sharing (CORS)

Quote from an MDN article:

Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional HTTP headers to tell a browser to let a web application running at one origin (domain) have permission to access selected resources from a server at a different origin. A web application makes a cross-origin HTTP request when it requests a resource that has a different origin (domain, protocol, and port) than its own origin.

By default, all origins, methods and headers are allowed. If you want more control you can adjust CORS-policy in Startup.cs.

More information can be found in the official documentation.

Dependency Injection

Dependency Injection is a form of inversion of control that supports the dependency inversion design principle.
This project uses Autofac as an IoC Container but it can be replaced with any other if you will.

First of all, you must configure a container. There are two methods to do this in the Startup.cs - ConfigureContainer and ConfigureProductionContainer. The later only gets called if your environment is Production. Read comments in these methods to get more information.

You can place your registration there directly, but I don't recommend that. According to the official documentation a recommended way is to use so called modules. The project already has a default module (Configuration\AutofacModules\DefaultModule.cs) that you can use for your own. Just register your components and services there and have fun. For example:

builder.RegisterType<Repo.ProductsRepo>().As<Repo.IProductsRepo>().SingleInstance();

If you add a new module, please, don't remember to add it to a container in one of the methods - ConfigureContainer or ConfigureProductionContainer:

builder.RegisterModule<DefaultModule>();

Second, you typically use registered types and interfaces in constructors of your controllers or of other services.

IProductsRepo ProductsRepo { get; }

public ProductsController(IProductsRepo productsRepo)
{
    ProductsRepo = productsRepo ?? throw new ArgumentNullException(nameof(productsRepo));
}

productsRepo parameter will be autowired by the container.

You can read more on this in the official Autofac documentation.

AutoMapper

When you create a web-service it is a common case to map one object to another. For example, you may want to map entity read from DB to DTO (Data Transmission Object) to return it as a response. You can write your own code to do that mapping or use a ready-made solution. Automapper is a solution to this problem.

Quote from the official site:

AutoMapper is a simple little library built to solve a deceptively complex problem - getting rid of code that mapped one object to another

The detailed information about using it in different cases you can get from an official documentation.

As an additional advantage of using Automapper, you get a segregation of mapping code from using it. Here we will focus on the most common cases and some simple examples to give you a starting point.

Automapper is already configured for you and ready to use. It is integrated with Autofac so you can inject IMapper interface to your services or controllers, or you can use Autofac to resolve services in mapping code! All the mapping code gathered in so called profiles. Profile is a class inherited from Automapper.Profile. The project already has one for demo purposes (see Configuration\AutoMapperProfiles\DefaultProfile.cs). You can use that one or add as many profiles as you want. To add profile you must create a new class derived from AutoMapper.Profile. At startup time your profile will be discovered and loaded automatically. If you want to use some service registered in DI-container just inject its interface in profile contructor.

Let's say for example you need to return Dto.Product object from some method of your controller, but you have Model.Product in your code. First of all, we should create a mapping from Model.Product to Dto.Product. This can be done in Configuration\AutoMapperProfiles\DefaultProfile.cs:

  CreateMap<Model.Product, Dto.Product>();

Second, use it in your controller:

  [HttpGet]
  public IEnumerable<Dto.Product> Get()
  {
      return ProductsRepo.Get().Select(Mapper.Map<Dto.Product>);
  }

Let's see a couple of examples of how to configure mappings:

cfg.CreateMap<Model.Product, Dto.Product>()
  // Using a custom constructor
  .ConstructUsing(src => new Dto.Product(src.Id))
  // Using a custom formatting
  .ForMember(x => x.Date, o => o.ResolveUsing((src, dest, destMember, context) =>
    $"{src.Year}-{src.Month:D2}-{src.Day:D2}"))
  // Calculated value from another fields of original object
  .ForMember(x => x.Contract, o => o.ResolveUsing((src, dest, destMember, context) =>
    $"{src.Contract.Number} from {src.Contract.Date}"))
  .AfterMap((src, dest, ctx) =>
  {
    // Resolve service from DI-container
    dest.SupplierName = c.Options.CreateInstance<ISuppliersRepo>().GetById(src.SupplierId);
  });

Logging

Each server in a production environment must log information messages and errors. There are many libraries to do this. This project template use Serilog. You don't need to do any configuration. All things are configured for you and will work without any additional configuration.

To use a logger you must inject ILogger<YourClass> interface into any controller or service as usual you don in any ASP.Net Core application. Here's an example:

public class ProductsContoller
{
  ILogger<ProductsContoller> Logger { get; }

  public ProductsContoller(ILogger<ProductsContoller> logger)
  {
    Logger = logger ?? throw new ArgumentNullException(nameof(logger));
  }

  public IActionResult Create(int id, [FromBody]Dto.UpdateProduct newProductDto)
  {
    // ... other code
    Logger.LogInformation("New product was created: {@product}", createdProduct);
    // some more code
  }
}

You can use Error, Warning and so on instead of Information in the example above. By default, Debug is used as a minimum log level for a development environment and Warning for a production one, but you can adjust it in appsettings.json file.

Log files are created in %AppData%/Logs folder, specific to the current process user. For example, if your server runs by AppService user than the folder will be C:\Users\AppService\AppData\Roaming\Logs. A name of the file is the same as a service main assembly name with '.txt' extension. Log files are rotated each day and the folder stores log files for last 30 days.

If you want you can change log file folder in settings as well as any other Serilog options. More information about using and configuring Serilog you can get in the official documentation.

Cache control

In most cases, you don't want to allow a browser to cache server responses. We use OWIN middleware to add cache-control header to all responses to any of GET requests. Middleware is implemented in Handlers/CacheControlMiddleware.cs file. It will be enough for most cases, but you can change it as needed.

Unhandled exceptions logging

If something went wrong and a server has crashed, we want to know what happens exactly and where it was. It is extremely helpful to log all unhandled exceptions. We do this by implementing IExceptionLogger interface and replacing a default implementation. You can see it in Handlers/ExceptionLogger.cs file.

Unhandled exceptions handling

By default WebApi 2 returns 500 Internal Server error HTTP status with the exception message and call stack in case of any exceptions. But this is not a recommended way to report errors for REST-services. Typically we want to return 401 status code if requested object not found, 403 if the action is not allowed and so on. We do this by implementing a global request filter. You can find it in Handlers/ExceptionFilter.cs file. The idea is simple. We just check whether an exception is one of the well-known types and, if so, create and return appropriate HTTP status and response.

Let's see an example:

public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
    if (actionExecutedContext.Exception is HttpResponseException)
    {
        actionExecutedContext.Response = (actionExecutedContext.Exception as HttpResponseException).Response;
        return;
    }

    var responseContent = new ErrorResponse(actionExecutedContext.Exception);
    var status = HttpStatusCode.InternalServerError;
    if(actionExecutedContext.Exception is KeyNotFoundException)
    {
        status = HttpStatusCode.NotFound;
    }

    actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(status, responseContent);
}

You should define your own exceptions and process them here to get the right HTTP status code.

Content formatting

Formatters are used by WebApi to deserialize data from request and to serialize responses. Generally, we want to use JSON for that, but WebApi uses XML as a default data format. Code in a App_Start/FormatterConfig.cs file removes XmlFormatter and set up some useful options for the JSON formatter.

Using environment variables in configuration options

"Build once - deploy anywhere" is a very useful principle that gives us the ability to easily deploy an app to any environment. Environment variables are a recommended way to store any config options that can vary from one environment to another. If you want to know more about this you can learn 12 Factor Apps Methodology.

Standard ConfigurationManager class does not expand environment variables that can be used in configuration options, so we need a wrapper to do this manually. A file Settings.cs contains helper methods and example settings that can use environment variables.

Let's see an example.

First, let's add some config option to web.config and use env var in it:

<appSettings>
  <add key="endpoint" value="http://%ENDPOINT_HOST%:8080" />
</appSettings>

Second, we should create a new property in class Settings.

public static class Settings
{
    public static string Get(string name) => Environment.ExpandEnvironmentVariables(ConfigurationManager.AppSettings[name] ?? "");
    public static string GetConnectionString(string name) => Environment.ExpandEnvironmentVariables(ConfigurationManager.ConnectionStrings[name]?.ConnectionString ?? "");

    public static string Endpoint => Get(Constants.Settings.Endpoint);

    // Other code...
  }
}

And of cause, we should add Constants.Settings.Endpoint constant in our Constants.cs.

Ok, now we are able to set up any options in environment variables but is there "the right" way to set env vars up? Of cause, we can set them up on OS-level and all will work fine. But it is not an only way to do this. In Unix-world, the dot-env files (.env) are a convenient way to set up environment variables. Luckily, we can use DotNetEnv NuGet-package to do the same thing on Windows.

All that we needed is to create a file with .env name and put it besides the web.config of our app. All configurations are already done in Startup.cs file.

So, let's create this file and add our variable from the example above:

ENDPOINT_HOST=localhost

After that the Settings.Endpoint property will return http://localhost:8080 value.

Documenting API

Documentation is a very useful thing for those who will use your API. But creating the documentation is a somewhat borrowing process. Moreover, once you wrote this documentation you have to publish it somewhere.

Swagger is a full and comprehensive solution to that problem. API documentation is one of the features. The full list of them you can find on the official site.

This project template use Swashbuckle. "Seamlessly adds a swagger to WebApi projects!" - as written in it's GitHub repo. This library does automatically create an interactive documentation for all controllers' actions and models as an HTML-page that is hosted within your service. You don't need to bother about hosting the documentation anymore. Your service turned self-documenting. You can use standard .Net comments to add more information.

Let's see an example.

In this line of code we set action's description:

/// <summary>
/// Getting complex type value
/// </summary>
[HttpGet]
[Route("GetComplex")]
public ComplexType GetComplex()
{
    return new ComplexType() { Key = "Key", Value = "Value" };
}

Here we are documenting properties of class ComplexType:

public class ComplexType
{
    /// <summary>
    /// This is the object's key
    /// </summary>
    public string Key { get; set; }
    // other attributes
}

To see a result you should run your service and navigate to http://localhost:5000/swagger/ui/index in your favorite browser. And magic appears :).

As in other cases, all aspects of Swashbuckle configuration gathered in App_Start/SwaggerConfig.cs file.