10 tips to kick-start your back end API with ServiceStack

| Facile Technolab Team | 4187 | 1

In this blog post, we will cover some helpful to tips kick start your new back-end API project with ServiceStack.

ServiceStackServiceStack is simple and fastest .Net web service framework. Because of many awesome features provided by {ServiceStack}, it has been very popular if you want to build back-end API in .Net. We recently started one of our cool project where ServiceStack is used for back-end. In this blog post, we will cover some helpful tips to kick start your new back-end API project with ServiceStack.

1. ServiceStackVS - Visual Studio Starter Kit

ServiceStackVS is a visual studio (supports 2012,2013,2015) extension that will save your time when you setup your project from scratch. It has many starter templates like:

  • Angular2 App
  • AngularJS App
  • Aurelia App
  • React App
  • React Desktop Apps
  • ASP.NET Empty
  • ServiceStack ASP.NET Empty
  • ServiceStack ASP.NET MVC4 & MVC5
  • ServiceStack ASP.NET with AngularJS
  • ServiceStack ASP.NET with Bootstrap
  • ServiceStack ASP.NET with Razor
  • ServiceStack Self Host Empty
  • ServiceStack Self Host with Razor
  • ServiceStack Windows Service Empty
We actually wanted to use Visual Studio 2017 Community edition and since this extension do not support it, we created a base project using Visual Studio 2015 and surprisingly, it worked without any problem in Visual Studio 2017 as well. We used ServiceStack ASP.NET MVC4 & MVC5 template and it created following projects in a single solution
  • {ProjectName} - A default asp.net mvc project with Nuget reference to all ServiceStack packages, AppHost.cs in the root
  • {ProjectName}.ServiceModel - A project to store request and response DTO classes. Hello.cs is there by default
  • {ProjectName}.ServiceInterface - A project to start actual services. MyService.cs is already there to expose Hello service.
  • {ProjectName}.Tests - A project for unit tests
After hitting F5 and locate to /api will show ServiceStack metadata page that has hello service listed! Great way to quickly get started! Have you tried any other templates? How is your experience with it?

 

2. Setting up Swagger API

Swagger API supports developer documentation, integrated test, request and response DTO and advance user experience while browsing API documentation.

Installation of the swagger package is quite straight forward as per the documentation. After installation of this package, I wanted to customize Swagger API's embedded resources to provide project specific branding from here. We used DownGit to copy the specific resource directory from github. Pasted entire folder into root of mvc project and adjusted index.html to point to ../api/resources path to automatically document services on launch.

3. Setting up Logging with NLog

It is quick and easy to follow ServiceStack Logging documentation to install nuget package and adjust the AppHost.cs After this configuration, I wanted to have NLog.config which took a little while to figure out. Here is the example NLog.config that I ended up with: Once this setup is done, you can use contructor inject or resolve ILog anywhere in your ServiceStack project.

Authentication & Authorization

Authentication & Authorization in ServiceStack is configurable. We inherited CredentialsAuthProvider provider to implement our own version of authentication provider. Our next 3 tips are around those configurations. Here is how our authentication configuration looks like:

4. Setup custom routes for login and log out

/api/auth, /api/authenticate, /api/auth/{Porivder}, /api/register, /api/assignrole, /api/unassignrole and /api/authenticate/{providers} are the default routes automatically added when you enable credentials authentication.
In our code, line 5-7 shows how we are replacing the login and logout service to custom routes /api/Account/Login and /api/Account/{Provider}" respectively.

5. Exclude Role and Registration related services

Line 5-7 in above code shows how to exclude role and registration service support from credentials authentication provider.

6. Setup other properties

You can configure other important settings like GenerateNewSessionCookiesOnAuthentication, DeleteSessionCookiesOnLogout, MaxLoginAttempts, ValidateUniqueEmails, ValidateUniqueUserNames etc.

7. Setup Credential Authentication Provider to return jwt tokens

With credentials authentication provider, only authenticated clients supporting cookies can consume your secure services.
In order to support cookieless/stateless authenticated services, we are implementing ServiceStack JWT Authentication and returning Bearer Token and Refresh Token in credential authentication response.
Here is the code that shows how we tweak credentials authentication provider to return bearer and refresh token upon successful login.
Register JwtAuthProvider right after credentials authentication provider.
In your custom user session class, add bearer token and refresh token properties.
And finally, use JWTAuthProvider object to set bearer and refresh token.
Set Authorization Bearer {token} header to call any secure service.

8. Fluent Migrations for Database Migrations

When you want to follow agile and do sprint wise development, its critical to have database versioning. Fluent Migrator is good option to use. We just came across this awesome implementation of Fluent Migrator for ServiceStack project in github which seems to be cool.

Unfortunately, I was not able to some dependency issues, I was not able to directly use it by adding it as nuget package but I was able to easily copy paste the service and it worked like a charm!
We already forked the project to see how we can help out to fix the issue to contribute back to the community.

9. Excluding routes from swagger and metadata

You can use [Exclude(Feature.Metadata)] attribute on request DTO to exclude service from metadata & swagger documentation.
If you want to exclude some services defined inside ServiceStack framework, you can use typeof(className).AddAttributes(new ExcludeAttribute(Feature.Metadata)); to exclude those services.

10. Return ISO dates in response instead of json dates

Another candidate to be included in the starter kit itself, here is the code:


Get free one hour consulting


We have experience of architecting and implementing many backend API services using ServiceStack. Feel free to connect with us for any kind of help!



Related posts


New comment


Comments

NeooMok

NeooMok
10/16/2019

Здесь вы можете заказать копию любого сайта под ключ, недорого и качественно, при этом не тратя свое время на различные программы и фриланс-сервисы.

Клонированию подлежат сайты как на конструкторах, так и на движках:
- Tilda (Тильда)
- Wix (Викс)
- Joomla (Джумла)
- Wordpress (Вордпресс)
- Bitrix (Битрикс)
и т.д.
телефон 8-996-725-20-75 звоните пишите viber watsapp
Копируются не только одностраничные сайты на подобии Landing Page, но и многостраничные. Создается полная копия сайта и настраиваются формы для отправки заявок и сообщений. Кроме того, подключается админка (админ панель), позволяющая редактировать код сайта, изменять текст, загружать изображения и документы.

Здесь вы получите весь комплекс услуг по копированию, разработке и продвижению сайта в Яндексе и Google.

Хотите узнать сколько стоит сделать копию сайта?
напишите нам
8-996-725-20-75 звоните пишите viber watsapp