Skip to main content

Custom .NET Controller

UPDATED: | POSTED: | by Serkan Munar

In this article, we will demonstrate how to extend the M.App Enterprise Server with a custom C#.NET Controller. Additionally, we will show how to protect the controller from external access using API Key Authentication.
Start Visual Studio and create a C# .NET Class Library project.
C# .NET Class Library
Install the NuGet Package Microsoft.AspNet.WebApi.Core for your project.
šŸ’”
We recommend to install version 5.2.9 if you want to add custom controller for M.App Enterprise 16.9 onwards
In order to derive from our .NET controller, the corresponding dependencies must be created in the project. To do this, go to the project in Visual Studio, right-click on ā€œReferencesā€ and select ā€œAdd Referenceā€¦ā€. In the following dialog, select the ā€œBrowseā€ option and add the two dll files, MApp.Code.dll and MApp.Endpoints.dll. You can find these in the bin directory in the installation folder of M.App Enterprise. We recommend copying the dll files to your own project directory first and creating the reference from there.
Add Reference to MApp.Core.dll and MApp.Endpoints.dll in your project
Create a C# class file and add following sample code, which contains a simple controller and an [HttpGet] action.
šŸ’”
Naming convention: If you create a custom controller, please make sure you always follow the ASP.NET naming convention. The class name of your controller must end with ā€˜Controllerā€™

using MApp.Endpoints;
using MApp.Core;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Web.Http;
using MApp.Data;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;

namespace CustomControllers
{
    [MAppAuthentication(AllowedClients.ApiKey)]
    public class CustomController : MAppTenantController
    {
        [HttpGet]
        [Route("api/v1/custom/action1")]
        public async Task<IHttpActionResult> Action1()
        {
            //Fetch and process data
            var responseObject = new
            {
                message = "Hello World!"
            };

            return this.JsonData(JsonConvert.SerializeObject(responseObject));
        }
    }
}

Now you have a custom controller which extends our basic controller MAppTenantController. In this example we also added an ApiKey authentication attribute, which limits the public access to the actions of this controller. So calling this action is only allowed with a valid access token.
āš ļø
An access token for your ApiKey authorization, can be created in M.App Enterprise StudioSecurityAPI Keys

Furthermore, it would also be possible to allow access only for requests from M.App Enterprise Apps. To do this, you need to change the authorization attribute to [MAppAuthentication(AllowedClients.App)] only.

The [Route("...")] attribute defines the public url for this action. In our case the http-get will be available at http://{YOUR MAE WEB PATH}/api/v1/custom/action1.

By extending from our basic controller MAppTenantController you get access to various functions and properties provided by M.App Enterprise Server.

For example:

Selecting the Database Connections stored in your M.App Enterprise environment.


List<Connection> connections = (await GetTenant().Database.SelectAsync<Connection>()).ToList();

Executing a SQL query command.


Database database = new Database({ConnectionString}, DbProviderType.PostgreSql);
database.ExecuteNonQuery("UPDATE mytable SET column1 = 'value1'");
Build your Visual Studio solution and copy the compiled .dll files to your M.App Enterprise installation directory and paste the files into the bin folder
šŸ’”
Any change in this directory leads to a rebuild of the M.App Enterprise Server. You might notice this, as the initial loading of an M.App Enterprise App or Studio could take a bit longer than usual.

After placing the .dll files into the bin folder of M.App Enterprise, your controller actions become available to be called.

As an example, you can call a function to fetch the data in your app:


  //custom script placed in M.App Enterprise AppEngine 
  function fetchData() {
    fetch('../api/v1/custom/action1', { 
      headers: { 
        'Tenant': {TENANT}, 
        'Authorization': `ApiKey {ACCESS TOKEN}` 
      } 
    })
    .then(response => {
        debugger;
        return response.json();
    })
    .then(data => {
        debugger;
        console.log(data);
    });
  }
  
  fetchData();
āš ļø
Replace {TENANT} with your tenant id and {ACCESS TOKEN} with your ApiKey token generated in M.App Enterprise Studio.

Congratulations! You have created your first custom controller and extended successfully our base M.App Enterprise controller.