Invoking a Custom API in Azure Mobile Service

The full scenario is that we have a task that needs to be performed by the Mobile Service that might take a while to complete. The first step is to define a custom api which will invoke the task (alternatively you could hijack a table controller to launch the task as part of one of the CRUD actions) and to have this called from the client applications. However, this alone is not sufficient for long running tasks as the call to the service may timeout before the task completes. I’ll come back to that in a future post but for now, let’s look at creating a custom api.

The first step is to add a new controller based on the Microsoft Azure Mobile Services Custom Controller template.

image

I’ll give the new controller a name

image

For the time being the only change I’ll make is to include the AutorizeLevel and AuthorizeInspector attributes to enforce the security policies required for accessing our services:

[AuthorizeLevel(AuthorizationLevel.User)]
[AuthorizeInspector]
public class ReporterController : ApiController
{
    public ApiServices Services { get; set; }

    // GET api/Reporter
    public async Task<string> Get()
    {
        Services.Log.Info(“Hello from custom controller!”);
        return “Hello”;
    }

}

Invoking this from the client can easily be done from within the MainViewModel:

public async void GenerateReport()
{
    string message;
    try
    {
        var result = await MobileService.InvokeApiAsync<string>(“Reporter”, HttpMethod.Get, null);
        message = result;
    }
    catch (MobileServiceInvalidOperationException ex)
    {
        message = ex.Message;
    }
    Debug.WriteLine(message);
}

Easy done – a simple api that we can invoke within our Mobile Service to do work. Note that in this case it’s a Get requrest with no parameters and a simple string return type. We can adjust this to be a Post, accept parameters and return a complex object by adjusting both the controller method definition (ie change Get to Post, or even just add a Post method) and invokeapiasync call.

Leave a comment