Web API Security Considerations for ASP.NET Web API

Avoid Revealing Software Version Numbers

Although this information may seem innocuous, it allows an attacker to identify the version of server side components and therefore target further attacks to this specific software. This can quickly lead to successful exploitation if the server side components have vulnerabilities with publicly available exploit code. The server software versions used by the application are revealed by the web server. Displaying version information of software information could allow an attacker to determine which vulnerabilities are present in the software, particularly if an outdated software version is in use with published vulnerabilities.

See the following guide for removing the headers from IIS and ASP.NET: https://blogs.msdn.microsoft.com/varunm/2013/04/23/removeunwanted-http-response-headers

Avoid Information Disclosure via Verbose Error Messages

It is recommended that functionality is implemented within the application that detects when an error has occurred and redirects the user to a custom error page that does not disclose any form of sensitive data. These errors that should induce a redirect to a custom error page should include 403 Forbidden Errors – to prevent an adversary from enumerating existing pages on the application that require prior authentication to view; 404 Not Found pages; and 500 Internal Error pages. Alternatively, simply redirecting a user to the applications home page can also suffice in reducing the level of information disclosed.

For ASP.NET, in web.config set one of the following options: 

<customErrors mode="RemoteOnly" />
<customErrors mode="On" />

Write out Security Headers

A number of HTTP Security Headers have been introduced in recent years to enhance security of a website by providing protections against certain types of attacks. The following table contains the headers which fall under this vulnerability category, notes are offered in the technical analysis as to which headers are missing and any misconfiguration discovered during the engagement.

It’s strongly recommended that these headers are configured on all applications to further harden the application from attack.

Few example headers that should be used:

  • Strict-Transport-Security – HTTP Strict-Transport-Security (HSTS) enforces secure (HTTP over SSL/TLS) connections to the server. This reduces impact of bugs in web applications leaking session data through cookies and external links and defends against Man-in-the-Middle attacks. HSTS also disables the ability for users to ignore SSL negotiation warnings
  • X-Frame-Options – improves the protection of web applications against Clickjacking. It declares a policy communicated from a host to the client browser on whether the browser must not display the transmitted content in frames of other web pages. This functionality can also be achieved with Content-Security-Policy.
  • X-XSS-Protection – enables the Cross-Site Scripting (XSS) filter that is built into most modern web browsers. Typically, the filter is enabled by default; the role of this header is to re-enable the filter if it was disabled by the user and also sets blocking mode which can mitigate some filter bypasses.
  • X-Content-Type-Options – The only defined value, “nosniff”, prevents Internet Explorer and Google Chrome from MIME-sniffing a response away from the declared content-type. This reduces exposure to cross-site scripting vulnerabilities that may not otherwise be present.
  • Content-Security-Policy – requires careful tuning and precise definition of the policy. If enabled, CSP has significant impact on the way browser renders pages (e.g., inline JavaScript disabled by default and must be explicitly allowed in policy). CSP prevents a wide range of attacks, including Cross-Site Scripting and other Cross-Site Injections.
  • Referrer-Policy – governs which referrer information, sent in the Referer header, should be included with requests made.

Additional information, plus examples of all headers to consider can be found at https://securityheaders.com

Use Cross-Site Request Forgery Protection

Cross-Site Request Forgery (CSRF) vulnerabilities arise when applications rely solely on HTTP cookies to identify the user that has issued a particular request. Because browsers automatically add cookies to requests regardless of their origin, it may be possible for an attacker to create a malicious web site that forges a cross-domain request to the vulnerable application. For a request to be vulnerable to CSRF, the following conditions must hold:

  • The request must be issued cross-domain, for example using an HTML form. If the request contains non-standard headers or body content and these are checked server-side, then it may only be issuable from a page that originated on the same domain.
  • The application must rely solely on HTTP cookies or Basic Authentication to identify the user that issued the request. If the application places session-related tokens within the request body, then it may not be vulnerable.
  • The request performs a privileged action within the application based on the identity of the issuing user.
  • The attacker can determine all the parameters required to construct a request that performs the action. If the request contains values that the attacker cannot determine or predict, then it is not vulnerable.

The most effective way to protect against CSRF vulnerabilities is to include within relevant requests an additional token that is not transmitted in a cookie: for example, a parameter in a hidden form field. This additional token should be random enough such that it is not feasible for an attacker to determine or predict the value of any token that was issued to another user. The token should be associated with the user’s session, and the application should validate that the correct token is received before performing any action resulting from the request.

An alternative approach, which may be easier to implement, is to validate that Host and Referer headers in relevant requests are both present and contain the same valid domain name. The Origin header can also be validated against the Host, however some browsers do not support this for requests made from the same domain, therefore this mechanism would need to use the Referer header as a fallback. For AJAX requests, a custom header can be added and then checked server-side (e.g. “X-Requested-With: XMLHttpRequest”), because this cannot be passed cross-domain without CORS being enabled.

However, these header checking approaches are somewhat less robust. Historically, quirks in browsers and implementation errors have often enabled attackers to forge cross-domain requests that manipulate these headers to bypass such defence.

Adventurous: Angular & .NET Core on Linux

Note: This article is not aiming on digging into details of setting up CI pipeline. It’s sole purpose is to explain my experience with deploying and running .NET Core app in Linux environment.

Another note: For the purpose of this article I created simple HelloWorld Web API (https://github.com/mattuu/HelloWorld.NetCoreApi) and simple HelloWorld Angular app (https://github.com/mattuu/HelloWorld.Angular) that calls this API.


This article will use following file system paths:

|--> api (directory for .NET Core Web API)
|--> www (directory for Angular app)
|--> nginx.conf (config file for Nginx)

Get you code over to Linux server

The CI pipeline should push your code to file system on Linux machine.

Deploying .NET Core 2.1 Web API to CentOS7

Install .NET Core runtime on CentOS server

This guide describes steps to install .NET Core: https://www.microsoft.com/net/download/linux-package-manager/centos/runtime-current

To check if .NET Core installed successfully, simply run:

dotnet --version

Now you should be able to start API by typing:

dotnet /usr/helloworld/api/HelloWorld.dll
Create dotnet daemon

Every process in Linux needs to run it’s own daemon. In order to accomplish this, we will use SystemD utility.

First we create service file helloworld.service with following content:

Description=Hello World .NET Core App Service

ExecStart=/usr/bin/dotnet /usr/helloworld/helloworld.dll 5000


Next we copy this file to SystemD location:

sudo cp helloworldapi.service /lib/systemd/system

Now we need to reload SystemD and enable the service:

sudo systemctl daemon-reload 
sudo systemctl enable helloworldapi

Finally we start the service and check the status:

sudo systemctl start helloworldapi 
systemctl status helloworldapi

More details of how to configure SystemD can be found here: https://www.freedesktop.org/wiki/Software/systemd/ or here: https://pmcgrath.net/running-a-simple-dotnet-core-linux-daemon

Install Proxy Server

Since .NET Core runs on Kestrel, we need to setup a web server that will act as reverse proxy for the API. Most commonly used are Nginx or Apache. I will use Nginx for this article.

Full instructions on how to install Nginx can be found here: http://nginx.org/en/docs/install.html

Configure Nginx to act as reverse proxy

Now we need to tell Nginx to forward requests to .NET Core application. By default .NET Core runs on port 5000 so below configuration should work fine (path: /usr/helloworld/nginx.conf)

location /api/ {
proxy_pass http://localhost:5000; proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $http_host;
proxy_cache_bypass $http_upgrade;

This ensures forwarding all requests to http://localhost/api are forwarded to http://localhost:5000 which is where .NET Core Web API is hosted.

Note: Nginx needs to be configured to include our custom configuration file so the following change needs to be done to Nginx default configuration (most likely to be in /etc/nginx/nginx.conf):

include /usr/helloworld/nginx.conf;

More on Nginx configuration options can be found here: https://nginx.org/en/docs/

Deploying Angular app to Centos7 OS

Our Angular app will be located in following directory: /usr/helloworld/www

Configure Nginx to serve static pages

Since Angular app is simple index.html, we need to tell Nginx to serve it as static content. Following article describes how to achieve this: https://medium.com/@jgefroh/a-guide-to-using-nginx-for-static-websites-d96a9d034940

Sample configuration may look like this (path: /usr/helloworld/nginx.conf)

location / {
root /usr/helloworld/www;
try_files /index.html =404;

location ~* .(js|jpg|png|css|woff|eot|svg|ttf|ico)$ {
root /usr/helloworld/www;
expires 30d;

First block ensures index.html is default document served by Nginx. This is needed to load Angular app properly.

Second line tells Nginx what to do with assets like JavaScript, CSS, images, fonts etc.

Once that’s done we should be able to navigate to http://localhost and see Angular app successfully loading:

If we now change browser url to http://localhost/?name=Matt, our application should display personalized greeting:

Our Angular app successfully passed name parameter to API and displayed greeting message generated by .NET Core.


I really think .NET Core on Linux has great potential and will be exploring it further in future. I am planning on creating some bash scripts for dealing with this setup.

Useful links

Automatic generation of EF entities and mappings from existing database schema

This is  a bunch of useful scripts for generating C# Entity Framework Code First POCOs from existing database schema.

First, let’s create T-SQL function for generating C# class for EF entity:

This function deliberately ignores certain columns, (Created On/By, Modified On/By). This properties are pushed to EntityBase class, which our POCO inherits from. All other columns in DB table will be mapped to corresponding C# type.

Next, let’s create T-SQL function for EF configuration (mapping class):

Now, let’s put it all together in one script:

All source code is available here

Unit Testing stack for C#/Visual Studio

After spending some time on digging through unit testing components, I ran into a setup I am finally happy with. This consists of:

https://github.com/AutoFixture – acts as DI container/object factory, significantly improving unit test maintainability

https://github.com/moq – awesome mocking framework, fully integrated with AutoFixture

https://www.nuget.org/packages/SemanticComparison – excellent utility for comparing instances

https://github.com/shouldly/shouldly – great for simplifying assertion statements

https://github.com/xunit/xunit – superb unit testing framework, supporting parameterized tests, multiple test executions and much more

Although each utility is great on it’s own, when combined together, this stack significantly reduces amount of testing code.

Below I include sample config file with latest versions of all packages.

<?xml version="1.0" encoding="utf-8"?>
    <package id="AutoFixture" version="3.50.2" targetFramework="net461" />
    <package id="AutoFixture.AutoMoq" version="3.50.2" targetFramework="net461" />
    <package id="AutoFixture.Idioms" version="3.50.2" targetFramework="net461" />
    <package id="AutoFixture.Xunit2" version="3.50.2" targetFramework="net461" />
    <package id="Moq" version="4.1.1308.2120" targetFramework="net461" />
    <package id="SemanticComparison" version="3.50.2" targetFramework="net461" />
    <package id="Shouldly" version="2.8.2" targetFramework="net461" />
    <package id="xunit" version="2.1.0" targetFramework="net461" />
    <package id="xunit.abstractions" version="2.0.0" targetFramework="net461" />
    <package id="xunit.assert" version="2.1.0" targetFramework="net461" />
    <package id="xunit.core" version="2.1.0" targetFramework="net461" />
    <package id="xunit.extensibility.core" version="2.1.0" targetFramework="net461" />
    <package id="xunit.extensibility.execution" version="2.1.0" targetFramework="net461" />
    <package id="xunit.runner.visualstudio" version="2.1.0" targetFramework="net461" />




Animated iPhone-style ImageButton with Silverlight 4

In this article I am presenting a way to create animated iPhone-style ImageButton control in Silverlight 4. Button will have icon on it, rounded corners and will zoom-in/zoom-out on hover. It will be done programmatically, with very minimum amount of XAML.

I start with creating ImageButton class. I use ButtonBase as base class:

Class declaration

I want my button to contain rounded rectangle with shadow and image on it. I add these items in constructor:

Class constructor

Now my control contains rectangle and image laid out over a grid to ensure proper items positioning. Next step is to add animation to enable zoom-in/out on hovering. This can be achieved with storyboards and double animations:


To start animations I need to start animations when mouse cursor enters or leaves control:


Very last step is making ImageSource property “bindable” so you can specify image from XAML. In order to do this I register new dependency property on my class:

Dependency property

The control then can be used in a following way:


And ready controls looks like this:

Final effect


WCF Custom tool error: Failed to generate code for the service reference.

Very recently, building multi-tier application involving Silverlight front-end inter-operating with WCF back-end, I encountered very odd, yet annoying behaviour of Visual Studio 2010. I was building new functionality using Telerik RadMap for Silverlight control that was to display some spartial data supplied by WCF service. To achieve this my Silverlight application had to reference few Telerik assemblies (Telerik.Windows.Controls.DataVisualization.dll). What is important is fact, that Service Reference for WCF service had been there already, project built and everything was working nicely, until I added extra method to WCF. After using “Update Service Reference” VS command, I started getting following error.

WCF error Screenshot no.1

Lack of further details with regards to this error and appropriate feedback from Visual Studio certainly does not help to get to the bottom of the problem, however after some investigation it turned out that one of Telerik assemblies caused this problem. When VS2010 creates service reference, default settings are that it should “reuse” all available types in reference. Excluding certain types from serialization allows service reference to be added successfully.

WCF error screen 2

I hope this helps anybody who got stuck with this problem.

SQL Data Types vs. C# Data Types

This article is just a reference of SQL Data Types to C# Data Types.

SQL Server data type CLR data type (SQL Server) CLR data type (.NET Framework)
varbinary SqlBytes, SqlBinary Byte[]
binary SqlBytes, SqlBinary Byte[]
varbinary(1), binary(1) SqlBytes, SqlBinary byte, Byte[]
image None None
varchar None None
char None None
nvarchar(1), nchar(1) SqlChars, SqlString Char, String, Char[]
nvarchar SqlChars, SqlString String, Char[]
nchar SqlChars, SqlString String, Char[]
text None None
ntext None None
uniqueidentifier SqlGuid Guid
rowversion None Byte[]
bit SqlBoolean Boolean
tinyint SqlByte Byte
smallint SqlInt16 Int16
int SqlInt32 Int32
bigint SqlInt64 Int64
smallmoney SqlMoney Decimal
money SqlMoney Decimal
numeric SqlDecimal Decimal
decimal SqlDecimal Decimal
real SqlSingle Single
float SqlDouble Double
smalldatetime SqlDateTime DateTime
datetime SqlDateTime DateTime
sql_variant None Object
User-defined type(UDT) user-defined type None
table None None
cursor None None
timestamp None None
xml SqlXml None


Interface vs. Abstract Class in .Net

In this article I will try to briefly explain main differences between interface and abstract class concepts in .Net. Although the differences can appear to be very subtle and little important, badly design inheritance can lead to massive problems and great mess in the code.

Abstract Class

Accordingly to MSDN abstract classes “are classes that cannot be instantiated (…), useful when creating components because they allow you specify an invariant level of functionality in some methods, but leave the implementation of other methods until a specific implementation of that class is needed. They also version well, because if additional functionality is needed in derived classes, it can be added to the base class without breaking code.”

Do declare abstract class following syntax is required:

abstract class Car()
    public Car() { };
    public string Make { get; set; }
    abstract public void Drive();

This class cannot be instantiated so following line will cause compiler throwing error:

Car a = new Car(); // this won’t compile

The only way to instantiate class Car is by creating child class that will inherit from it:

public class OffRoadCar : Car
    public OffRoadCar();
    public void Switch4WD(bool On)
        // method code

Because class OffRoadCar inherits from Car, following code will work:

OffRoadCar offroader = new OffRoadCar();
offroader.Switch4WD(true); // from OffRoadClass
offroader.Drive(); // from Car class


Interface, after MSDN, is a “definition that can never change after the interface definition has been released. This interface invariance is an important principle of component design, because it protects existing systems that have been written to use the interface.”

Interface cannot be instantiated, but serve as sort of pattern for derived classes, that share and implement specific features. Derived classes can also extend interface functionality, by defining extra members. Following code demonstrates sample interface:

public interface ICar
    string Make { get; set; }
    void Drive();

Because interface can serve as a “template” for series of classes, implementing it is a way of ensuring that all derived object will have set of common features. In example:

public class SportsCar : ICar
    public string Make { get; set; } // required from ICar
    public bool IsConvertible { get; set; } // adds extra feature
    public void Drive() // required by ICar


public class Van : ICar
    public string Make { get; set; } // required from ICar
    public double LoadWeight { get; set; } // adds extra feature
    public void Drive() // required by ICar


Because both SportsCar and Van classes inherit from ICar interface, they are forced to have common set of features (Make property and Drive() method). Thanks to that it is possible to write:

List<ICar> vehicles = new {
    new SportsCar() { Make = "Ferrari", IsConvertible = false },
    new Van() { Make = "Ford", LoadWeight = 3000 }

foreach(ICar car in vehicles)


In opposite to abstract class, interface cannot implement any default functionality in its methods. It also cannot implement default constructor. This is why we say we implement interface and inherit from abstract class.

Class may implement an unlimited number of interfaces, but may inherit from only one abstract class. A class that is derived from an abstract class may still implement interfaces.

Abstract classes and interfaces play extremely important role in programming concept called polymorphism, which in essence is “ability for classes to provide different implementations of methods that are called by the same name” (MSDN).