Skip to content
Sergey Tregub edited this page May 23, 2020 · 23 revisions

Getting started

The template uses the 4.7.1 version of .Net Framework, so you should have it installed.

  1. Install the extension from the Visual Studio Marketplace or download and install the latest version from the GitHub. Also, you can install it from Visual Studio. To do so click on "Tools/Extensions and Updates..." menu item, then select "Online/Visual Studio Marketplace/Templates" on the left pane, search for "ASP.Net WebAPI Application Project Template," select it and click "Download" button.
  2. Restart Visual Studio
  3. Click on "File/New Project..." menu item
  4. Type "webapi" on the right pane
  5. Select "APS.Net WebAPI Application With OWIN" and click OK button.
  6. Run the service
  7. Open a browser and navigate to http://localhost:5000/swagger/ui/index to see API documentation
  8. Play around with the API

Visit project Wiki pages to learn more about the template.

Using PackageReference instead of package.config

The project uses PackageReference instead of package.config file. Using the PackageReference has some advantages as well as some compatibility issues, so be aware of that. For example, if you install an EntityFramework you should add configutation in "web.config" manually (see below).

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 are allowed. You can set up origin by uncommenting this line in web.config. To specify more than one origin split them by semicolon.

For example:

  <appSettings>
    <add key="allowed-origins" value="http://localhost:5000; https://api.some-domain.com"/>
  </appSettings>

If you want more control you can adjust CORS-policy in App_Start/CorsConfig.cs.

More information can be found here.

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, you should to configure the container. It can be done in RegisterServices method in App_Start/AutofacConfig.cs file.

For example:

builder.RegisterType<FileStore>().As<IFileStore>().SingleInstance();
builder.RegisterType<ImageMetadataLoader>().As<IImageMetadataLoader>();
builder.RegisterType<ImageRotationService>().AsSelf();

Second, you typically use registered types and interfaces in constructors of your controllers. One service can use another that way of course.

For more complex scenarios and examples see the official documentation.

IImageMetadataLoader MetadataLoader { get; }

public ProductsController(IImageMetadataLoader metadataLoader)
{
    MetadataLoader = metadataLoader ?? throw new ArgumentNullException(nameof(metadataLoader));
}

metadataLoader 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 mapper to your services or controllers, or you can use Autofac to resolve services in mapping code! Let's see a simple example of how to achieve this.

Let's say you need to return Dto.Product object from some method of your controller, but you have Model.Product in your code. First, you should create a mapping from Model.Product to Dto.Product. This can be done in the Configure method in App_Start/AutomapperConfig.cs:

public static IMapper Configure(HttpConfiguration config)
{
    Action<IMapperConfigurationExpression> mapperConfigurationExp = cfg =>
    {
        cfg.ConstructServicesUsing(GetResolver(config));

        // TODO: Create mappings here
        // For more information see https://github.com/drwatson1/AspNet-WebApi/wiki#automapper

        // New line of code. Detailed configuration skipped for simplicity
        cfg.CreateMap<Model.Product, Dto.Product>();
    };

    var mapperConfiguration = new MapperConfiguration(mapperConfigurationExp);
    Mapper = mapperConfiguration.CreateMapper();

    return Mapper;
}

Second, use it in your controller:

public class ProductsController: ApiController
{
  IMapper Mapper { get; }
  IProductsRepo Repo { get; }

  public ProductsController(IMapper mapper, IProductsRepo repo)
  {
    Mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
    Repo = repo ?? throw new ArgumentNullException(nameof(repo));
  }

  [HttpGet]
  public Dto.Product Get(int key)
  {
    return Mapper.Map<Dto.Product>(Repo.GetById(key))
  }

  [HttpGet]
  public IEnumerable<Dto.Product> Get()
  {
    return Repo.Get(key).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 perform any configuration. All things are configured for you and will work without any additional configuration.

There are two ways to use logger. First, you can inject ILogger interface into any controller or service (preferred way), or, second, you can use a global object Log.Logger. You should avoid using the global object. Here are the examples:

public class ProductsContoller
{
  ILogger Logger { get; }

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

  [HttpGet]
  public Dto.Product Get(int key)
  {
    Logger.Information("Product with id='{key}' is requested", key);
    // Other code
  }
}

You can use Error, Warning and so on instead of Information in the example above. By default, Information is used as a minimum log level, but you can adjust it in this line in the web.config 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 the last 30 days.

If you want you can change any configuration option in App_Start/LoggerConfig.cs file.

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.

Using EntityFramework

Because the project uses PackageReference instead of packages.config when you add a reference to an EntityFramework NuGet-package, the "web.config" file is not modified. So you need to add EF configuration manually. Here is an example:

  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
  <connectionStrings>
    <add name="MyContext" providerName="System.Data.SqlClient" connectionString="data source=(localdb)\MyDb;initial catalog=MyDb;;Integrated Security=True" />
  </connectionStrings>

The reason of that is described in official documentation:

With PackageReference, install.ps1 and uninstall.ps1 PowerShell scripts are not executed while installing or uninstalling a package.