Reference documentation

How to: Create a .NET Mobile App backend

If you are starting a new project, you can create an App Service application using either the Azure portal or Visual Studio. You can run
the App Service application locally or publish the project to your cloud-based App Service mobile app.

In the Settings pane for the new Mobile Apps back end, select Quick start > your client app platform > Connect a database.

In the Add data connection pane, select SQL Database > Create a new database. Enter the database name, choose a pricing tier, and then select Server. You can reuse this new database. If you already have a database in the same location, you can instead choose Use an existing database. We don't recommend the use of a database in a different location, due to bandwidth costs and higher latency.

In the New server pane, enter a unique server name in the Server name box, provide a login and password, select Allow Azure services to access server, and select OK. This step creates the new database.

Back in the Add data connection pane, select Connection string, enter the login and password values for your database, and select OK.

Wait a few minutes for the database to be deployed successfully before you proceed.

Back in the Get started blade, under Create a table API, choose C# as your Backend language. Click Download, extract the
compressed project files to your local computer, and open the solution in Visual Studio.

Create a .NET backend using Visual Studio 2017

Install the Azure workload via the Visual Studio Installer to publish to Azure Mobile Apps project from Visual Studio. Once you
have installed the SDK, create an ASP.NET application using the following steps:

Open the New Project dialog (from File > New > Project...).

Expand Visual C# and select Web.

Select ASP.NET Web Application (.NET Framework).

Fill in the project name. Then click OK.

Select Azure Mobile App from the list of templates.

Click OK to create the solution.

Right-click on the project in the Solution Explorer and choose Publish..., then choose App Service as the publishing target.

Follow the prompts to authenticate and choose a new or existing Azure App Service to publish.

Create a .NET backend using Visual Studio 2015

Install the Azure SDK for .NET (version 2.9.0 or later) to create an Azure Mobile Apps project in Visual Studio. Once you
have installed the SDK, create an ASP.NET application using the following steps:

Open the New Project dialog (from File > New > Project...).

Expand Templates > Visual C#, and select Web.

Select ASP.NET Web Application.

Fill in the project name. Then click OK.

Under ASP.NET 4.5.2 Templates, select Azure Mobile App. Check Host in the cloud to create a mobile backend in the cloud to which you can publish this project.

Click OK.

How to: Download and initialize the SDK

The SDK is available on NuGet.org. This package includes the base functionality required to get started using the SDK. To initialize the SDK, you
need to perform actions on the HttpConfiguration object.

Install the SDK

To install the SDK, right-click on the server project in Visual Studio, select Manage NuGet Packages, search for the Microsoft.Azure.Mobile.Server
package, then click Install.

Initialize the server project

A .NET backend server project is initialized similar to other ASP.NET projects, by including an OWIN startup class. Ensure that you have referenced
the NuGet package Microsoft.Owin.Host.SystemWeb. To add this class in Visual Studio, right-click on your server project and select Add >
New Item, then Web > General > OWIN Startup class. A class is generated with the following attribute:

[assembly: OwinStartup(typeof(YourServiceName.YourStartupClassName))]

In the Configuration() method of your OWIN startup class, use an HttpConfiguration object to configure the Azure Mobile Apps environment.
The following example initializes the server project with no added features:

To enable individual features, you must call extension methods on the MobileAppConfiguration object before calling ApplyTo. For example,
the following code adds the default routes to all API controllers that have the attribute [MobileAppController] during initialization:

new MobileAppConfiguration()
.MapApiControllers()
.ApplyTo(config);

The server quickstart from the Azure portal calls UseDefaultConfiguration(). This equivalent to the following setup:

new MobileAppConfiguration()
.AddMobileAppHomeController() // from the Home package
.MapApiControllers()
.AddTables( // from the Tables package
new MobileAppTableConfiguration()
.MapTableControllers()
.AddEntityFramework() // from the Entity package
)
.AddPushNotifications() // from the Notifications package
.MapLegacyCrossDomainController() // from the CrossDomain package
.ApplyTo(config);

SDK extensions

The following NuGet-based extension packages provide various mobile features that can be used by your application. You enable extensions during
initialization by using the MobileAppConfiguration object.

Microsoft.Azure.Mobile.Server.Quickstart
Supports the basic Mobile Apps setup. Added to the configuration by calling the UseDefaultConfiguration extension method during
initialization. This extension includes following extensions: Notifications, Authentication, Entity, Tables, Cross-domain, and Home
packages. This package is used by the Mobile Apps Quickstart available on the Azure portal.

Microsoft.Azure.Mobile.Server.Home
Implements the default this mobile app is up and running page for the web site root. Add to the configuration by calling the
AddMobileAppHomeController extension method.

Microsoft.Azure.Mobile.Server.Entity
Enables the Entity Framework to access data in the SQL Database. Add to the configuration by calling the AddTablesWithEntityFramework extension method.

Microsoft.Azure.Mobile.Server.Authentication
Enables authentication and sets-up the OWIN middleware used to validate tokens. Add to the configuration by calling the AddAppServiceAuthentication
and IAppBuilder.UseAppServiceAuthentication extension methods.

Microsoft.Azure.Mobile.Server.CrossDomain
Creates a controller that serves data to legacy web browsers from your Mobile App. Add to the configuration by calling the
MapLegacyCrossDomainController extension method.

How to: Publish the server project

This section shows you how to publish your .NET backend project from Visual Studio. You can also deploy your backend project using Git or any of
the other methods available there.

In Visual Studio, rebuild the project to restore NuGet packages.

In Solution Explorer, right-click the project, click Publish. The first time you publish, you need to define a publishing profile. When
you already have a profile defined, you can select it and click Publish.

The DTO is used to define the table within the SQL database. To create the database entry, add a DbSet<> property to
the DbContext you are using. In the default project template for Azure Mobile Apps, the DbContext is called Models\MobileServiceContext.cs:

If you have the Azure SDK installed, you can now create a template table controller as follows:

Right-click on the Controllers folder and select Add > Controller....

Select the Azure Mobile Apps Table Controller option, then click Add.

In the Add Controller dialog:

In the Model class dropdown, select your new DTO.

In the DbContext dropdown, select the Mobile Service DbContext class.

The Controller name is created for you.

Click Add.

The quickstart server project contains an example for a simple TodoItemController.

How to: Adjust the table paging size

By default, Azure Mobile Apps returns 50 records per request. Paging ensures that the client does not tie up their UI thread nor the server for
too long, ensuring a good user experience. To change the table paging size, increase the server side "allowed query size" and the client-side page size
The server side "allowed query size" is adjusted using the EnableQuery attribute:

[EnableQuery(PageSize = 500)]

Ensure the PageSize is the same or larger than the size requested by the client. Refer to the specific client HOWTO documentation
for details on changing the client page size.

How to: Define a custom API controller

The custom API controller provides the most basic functionality to your Mobile App backend by exposing an endpoint. You can register a
mobile-specific API controller using the [MobileAppController] attribute. The MobileAppController attribute registers the route, sets
up the Mobile Apps JSON serializer, and turns on client version checking.

In App_Start/Startup.MobileApp.cs file, add a call to the MapApiControllers extension method, as in the following example:

new MobileAppConfiguration()
.MapApiControllers()
.ApplyTo(config);

You can also use the UseDefaultConfiguration() extension method instead of MapApiControllers(). Any controller that does not have
MobileAppControllerAttribute applied can still be accessed by clients, but it may not be correctly consumed by clients using any
Mobile App client SDK.

How to: Add authentication to a server project

You can add authentication to your server project by extending the MobileAppConfiguration object and configuring OWIN middleware. When
you install the Microsoft.Azure.Mobile.Server.Quickstart package and call the UseDefaultConfiguration extension method, you can skip
to step 3.

How to: Use custom authentication for your application

Important

In order to enable custom authentication, you must first enable App Service Authentication without selecting a provider for your App Service in the Azure portal. This will enable the WEBSITE_AUTH_SIGNING_KEY environment variable when hosted.

If you do not wish to use one of the App Service Authentication/Authorization providers, you can implement your own login system. Install
the Microsoft.Azure.Mobile.Server.Login package to assist with authentication token generation. Provide your own code for validating
user credentials. For example, you might check against salted and hashed passwords in a database. In the example below, the isValidAssertion()
method (defined elsewhere) is responsible for these checks.

The custom authentication is exposed by creating an ApiController and exposing register and login actions. The client should use
a custom UI to collect the information from the user. The information is then submitted to the API with a standard HTTP POST call. Once
the server validates the assertion, a token is issued using the AppServiceLoginHandler.CreateToken() method. The ApiController should not
use the [MobileAppController] attribute.

The AppServiceLoginHandler.CreateToken() method includes an audience and an issuer parameter. Both of these parameters are set to the URL
of your application root, using the HTTPS scheme. Similarly you should set secretKey to be the value of your application's signing key. Do not
distribute the signing key in a client as it can be used to mint keys and impersonate users. You can obtain the signing key while hosted in App
Service by referencing the WEBSITE_AUTH_SIGNING_KEY environment variable. If needed in a local debugging context, follow the instructions in
the Local debugging with authentication section to retrieve the key and store it as an application setting.

The issued token may also include other claims and an expiry date. Minimally, the issued token must include a subject (sub) claim.

You can support the standard client loginAsync() method by overloading the authentication route. If the client calls client.loginAsync('custom');
to log in, your route must be /.auth/login/custom. You can set the route for the custom authentication controller using MapHttpRoute():

Using the loginAsync() approach ensures that the authentication token is attached to every subsequent call to the service.

How to: Retrieve authenticated user information

When a user is authenticated by App Service, you can access the assigned user ID and other information in your .NET backend code. The user
information can be used for making authorization decisions in the backend. The following code obtains the user ID associated with a request:

// Get the SID of the current user.
var claimsPrincipal = this.User as ClaimsPrincipal;
string sid = claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier).Value;

The SID is derived from the provider-specific user ID and is static for a given user and login provider. The SID is null for invalid
authentication tokens.

App Service also lets you request specific claims from your login provider. Each identity provider can provide more information using the
identity provider SDK. For example, you can use the Facebook Graph API for friends information. You can specify claims that are requested
in the provider blade in the Azure portal. Some claims require additional configuration with the identity provider.

The following code calls the GetAppServiceIdentityAsync extension method to get the login credentials, which include the access token
needed to make requests against the Facebook Graph API:

Add a using statement for System.Security.Principal to provide the GetAppServiceIdentityAsync extension method.

How to: Restrict data access for authorized users

In the previous section, we showed how to retrieve the user ID of an authenticated user. You can restrict access to data and other
resources based on this value. For example, adding a userId column to tables and filtering the query results by the user ID is
a simple way to limit returned data only to authorized users. The following code returns data rows only when the SID matches the
value in the UserId column on the TodoItem table:

// Get the SID of the current user.
var claimsPrincipal = this.User as ClaimsPrincipal;
string sid = claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier).Value;
// Only return data rows that belong to the current user.
return Query().Where(t => t.UserId == sid);

The Query() method returns an IQueryable that can be manipulated by LINQ to handle filtering.

How to: Enable targeted push using Tags

Notification Hubs lets you send targeted notifications to specific registrations by using tags. Several tags are created automatically:

The Installation ID identifies a specific device.

The User Id based on the authenticated SID identifies a specific user.

The installation ID can be accessed from the installationId property on the MobileServiceClient. The following example shows how to
use an installation ID to add a tag to a specific installation in Notification Hubs:

Any tags supplied by the client during push notification registration are ignored by the backend when creating the installation. To enable a client
to add tags to the installation, you must create a custom API that adds tags using the preceding pattern.

How to: Send push notifications to an authenticated user

When an authenticated user registers for push notifications, a user ID tag is automatically added to the registration. By using
this tag, you can send push notifications to all devices registered by that person. The following code gets the SID of user making the
request and sends a template push notification to every device registration for that person:

When registering for push notifications from an authenticated client, make sure that authentication is complete before attempting
registration. For more information, see Push to users in the App Service Mobile Apps completed quickstart sample for .NET backend.

How to: Debug and troubleshoot the .NET Server SDK

Azure App Service provides several debugging and troubleshooting techniques for ASP.NET applications:

Local debugging with authentication

You can run your application locally to test changes before publishing them to the cloud. For most Azure Mobile Apps backends, press F5 while
in Visual Studio. However, there are some additional considerations when using authentication.

You must have a cloud-based mobile app with App Service Authentication/Authorization configured, and your client must have the cloud endpoint
specified as the alternate login host. See the documentation for your client platform for the specific steps required.

Ensure that your mobile backend has Microsoft.Azure.Mobile.Server.Authentication installed. Then, in your application's OWIN startup class,
add the following, after MobileAppConfiguration has been applied to your HttpConfiguration:

In the preceding example, you should configure the authAudience and authIssuer application settings within your Web.config file to each be the
URL of your application root, using the HTTPS scheme. Similarly you should set authSigningKey to be the value of your application's signing key.
To obtain the signing key:

Use the signing key for the authSigningKey parameter in your local application config. Your mobile backend is now equipped to validate
tokens when running locally, which the client obtains the token from the cloud-based endpoint.