使用适用于 Azure 移动应用的 .NET 后端服务器 SDKWork with the .NET backend server SDK for Azure Mobile Apps

本主题说明如何在关键的 Azure 应用服务移动应用方案中使用 .NET 后端服务器 SDK。This topic shows you how to use the .NET backend server SDK in key Azure App Service Mobile Apps scenarios. 借助 Azure 移动应用 SDK 可从 ASP.NET 应用程序使用移动客户端。The Azure Mobile Apps SDK helps you work with mobile clients from your ASP.NET application.

Tip

适用于 Azure 移动应用的 .NET 服务器 SDK 是 GitHub 上的开放源代码。The .NET server SDK for Azure Mobile Apps is open source on GitHub. 存储库包含所有源代码,包括整个服务器 SDK 单元测试套件以及一些示例项目。The repository contains all source code including the entire server SDK unit test suite and some sample projects.

参考文档Reference documentation

服务器 SDK 的参考文档位于此处:Azure 移动应用 .NET 参考The reference documentation for the server SDK is located here: Azure Mobile Apps .NET Reference.

如何:创建 .NET 移动应用后端How to: Create a .NET Mobile App backend

如果正在开始新项目,可以使用 Azure 门户 或 Visual Studio 创建应用服务应用程序。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.

如果将移动功能添加到现有项目,请参阅下载并初始化 SDK 部分。If you are adding mobile capabilities to an existing project, see the Download and initialize the SDK section.

使用 Azure 门户创建 .NET 后端Create a .NET backend using the Azure portal

若要创建应用服务移动后端,请按照快速入门教程或以下步骤操作:To create an App Service mobile backend, either follow the Quickstart tutorial or follow these steps:

  1. 登录到 Azure 门户Sign in at the Azure portal.

  2. 单击“+新建” > “Web + 移动” > “移动应用”,并为移动应用后端提供一个名称。 Select +NEW > Web + Mobile > Mobile App, and then provide a name for your Mobile Apps back end.

  3. 在“资源组”下 ,选择一个现有资源组,或创建一个新资源组(使用与应用相同的名称)。For Resource Group, select an existing resource group, or create a new one (by using the same name as your app).

  4. 对于“应用服务计划” ,请选择默认计划(在标准层中)。For App Service plan, the default plan (in the Standard tier) is selected. 还可以选择其他计划,或创建一个新计划You can also select a different plan, or create a new one.

    应用服务计划的设置将确定与应用关联的位置、功能、成本和计算资源The App Service plan's settings determine the location, features, cost, and compute resources associated with your app. 有关应用服务计划以及如何在不同定价层和所需位置中创建新计划的详细信息,请参阅 Azure 应用服务计划深入概述For more about App Service plans and how to create a new plan in a different pricing tier and in your desired location, see Azure App Service plans in-depth overview.

  5. 选择“创建” 。Select Create. 此步骤创建移动应用后端。This step creates the Mobile Apps back end.

  6. 在新的移动应用后端的“设置”窗格中,依次选择“快速启动”>客户端应用平台 >“连接数据库”。 In the Settings pane for the new Mobile Apps back end, select Quick start > your client app platform > Connect a database.

    用于连接数据库的选项选择

  7. 在“添加数据连接” 窗格中,选择“SQL 数据库” > “创建新数据库”。 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.

    选择数据库

  8. 在“新服务器”窗格中,在“服务器名称”框中输入唯一服务器名称,提供登录名和密码,选中“允许 Azure 服务访问服务器”,并选择“确定”。 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.

  9. 回到“添加数据连接”窗格中,选择“连接字符串”,输入数据库的登录名和密码值,并选择“确定”。 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.

返回“开始使用” 边栏选项卡,在“创建表 API” 下选择“C#” 作为“后端语言” 。Back in the Get started blade, under Create a table API, choose C# as your Backend language. 单击“下载” ,将压缩的项目文件解压缩到本地计算机,并在 Visual Studio 中打开解决方案。Click Download, extract the compressed project files to your local computer, and open the solution in Visual Studio.

使用 Visual Studio 2017 创建 .NET 后端Create a .NET backend using Visual Studio 2017

通过 Visual Studio 安装程序安装 Azure 工作负荷,以从 Visual Studio 发布到 Azure 移动应用项目。Install the Azure workload via the Visual Studio Installer to publish to Azure Mobile Apps project from Visual Studio. 安装 SDK 后,使用以下步骤创建 ASP.NET 应用程序:Once you have installed the SDK, create an ASP.NET application using the following steps:

  1. 从“文件” > “新建” > “项目...” ,打开“新建项目” 对话框。Open the New Project dialog (from File > New > Project...).
  2. 展开“Visual C#”,然后选择“Web” 。Expand Visual C# and select Web.
  3. 选择“ASP.NET Web 应用程序(.NET Framework)” 。Select ASP.NET Web Application (.NET Framework).
  4. 填写项目名称。Fill in the project name. Then click OK.
  5. 从模板列表中选择“Azure 移动应用” 。Select Azure Mobile App from the list of templates.
  6. 单击“确定”创建解决方案 。Click OK to create the solution.
  7. 右键单击解决方案资源管理器中的项目,并选择“发布...”,然后选择“应用服务”作为发布目标 。Right-click on the project in the Solution Explorer and choose Publish..., then choose App Service as the publishing target.
  8. 按照提示进行身份验证,然后选择新的或现有的 Azure 应用服务进行发布。Follow the prompts to authenticate and choose a new or existing Azure App Service to publish.

使用 Visual Studio 2015 创建 .NET 后端Create a .NET backend using Visual Studio 2015

安装用于 .NET 的 Azure SDK(2.9.0 版或更高版本),在 Visual Studio 中创建 Azure 移动应用项目。Install the Azure SDK for .NET (version 2.9.0 or later) to create an Azure Mobile Apps project in Visual Studio. 安装 SDK 后,使用以下步骤创建 ASP.NET 应用程序:Once you have installed the SDK, create an ASP.NET application using the following steps:

  1. 打开“新建项目” 对话框(从“文件” > “新建” > “项目...” )。Open the New Project dialog (from File > New > Project...).
  2. 展开“模板” > “Visual C#” ,然后选择“Web” 。Expand Templates > Visual C#, and select Web.
  3. 选择“ASP.NET Web 应用程序” 。Select ASP.NET Web Application.
  4. 填写项目名称。Fill in the project name. Then click OK.
  5. 在“ASP.NET 4.5.2 模板” 下,选择“Azure 移动应用” 。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.
  6. 单击 “确定”Click OK.

如何:下载并初始化 SDKHow to: Download and initialize the SDK

该 SDK 在 NuGet.org上提供。此包包含开始使用 SDK 所需的基本功能。The SDK is available on NuGet.org. This package includes the base functionality required to get started using the SDK. 若要初始化该 SDK,需要对 HttpConfiguration 对象执行操作。To initialize the SDK, you need to perform actions on the HttpConfiguration object.

安装 SDKInstall the SDK

若要安装该 SDK,请在 Visual Studio 中右键单击服务器项目,选择“管理 NuGet 包” ,搜索 Microsoft.Azure.Mobile.Server 包,然后单击“安装” 。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

初始化 .NET 后端服务器项目的方式类似其他 ASP.NET 项目,可通过包含 OWIN 启动类来完成。A .NET backend server project is initialized similar to other ASP.NET projects, by including an OWIN startup class. 确保已引用 NuGet 包 Microsoft.Owin.Host.SystemWebEnsure that you have referenced the NuGet package Microsoft.Owin.Host.SystemWeb. 若要在 Visual Studio 中添加此类,请右键单击服务器项目,选择 “添加” > “新建项” ,然后选择 “Web” > “常规” > “OWIN 启动类”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))]

在 OWIN startup 类的 Configuration() 方法中,使用 HttpConfiguration 对象配置 Azure 移动应用环境。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:

// in OWIN startup class
public void Configuration(IAppBuilder app)
{
    HttpConfiguration config = new HttpConfiguration();

    new MobileAppConfiguration()
        // no added features
        .ApplyTo(config);

    app.UseWebApi(config);
}

若要启用各个功能,必须在调用 ApplyTo 之前对 MobileAppConfiguration 对象调用扩展方法 。To enable individual features, you must call extension methods on the MobileAppConfiguration object before calling ApplyTo. 例如,以下代码在初始化期间,将默认路由添加到具有属性 [MobileAppController] 的所有 API 控制器: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);

Azure 门户中的服务器快速启动调用 UseDefaultConfiguration() 。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);

使用的扩展方法包括:The extension methods used are:

  • AddMobileAppHomeController() 提供默认的 Azure 移动应用主页。AddMobileAppHomeController() provides the default Azure Mobile Apps home page.
  • MapApiControllers(),用于为使用 [MobileAppController] 属性修饰的 WebAPI 控制器提供自定义 API 功能。MapApiControllers() provides custom API capabilities for WebAPI controllers decorated with the [MobileAppController] attribute.
  • AddTables(),用于提供到表控制器的 /tables 终结点映射。AddTables() provides a mapping of the /tables endpoints to table controllers.
  • AddTablesWithEntityFramework(),是使用基于实体框架的控制器映射 /tables 终结点的简单方法。AddTablesWithEntityFramework() is a short-hand for mapping the /tables endpoints using Entity Framework based controllers.
  • AddPushNotifications(),提供了一种向通知中心注册设备的简单方法。AddPushNotifications() provides a simple method of registering devices for Notification Hubs.
  • MapLegacyCrossDomainController() 为本地开发提供标准 CORS 标头。MapLegacyCrossDomainController() provides standard CORS headers for local development.

SDK 扩展SDK extensions

以下基于 NuGet 的扩展包提供应用程序可以使用的多种移动功能。The following NuGet-based extension packages provide various mobile features that can be used by your application. 可以使用 MobileAppConfiguration 对象在初始化期间启用扩展。You enable extensions during initialization by using the MobileAppConfiguration object.

  • Microsoft.Azure.Mobile.Server.Quickstart 支持基本的移动应用设置。Microsoft.Azure.Mobile.Server.Quickstart Supports the basic Mobile Apps setup. 在初始化期间,通过调用 UseDefaultConfiguration 扩展方法添加到配置。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. Azure 门户上提供的移动应用快速入门使用此包。This package is used by the Mobile Apps Quickstart available on the Azure portal.

  • Microsoft.Azure.Mobile.Server.Home 实现网站根目录的默认 此移动应用已启动并在运行 页。Microsoft.Azure.Mobile.Server.Home Implements the default this mobile app is up and running page for the web site root. 通过调用 AddMobileAppHomeController 扩展方法添加到配置。Add to the configuration by calling the AddMobileAppHomeController extension method.

  • Microsoft.Azure.Mobile.Server.Tables 包含用于处理数据和设置数据管道的类。Microsoft.Azure.Mobile.Server.Tables includes classes for working with data and sets-up the data pipeline. 通过调用 AddTables 扩展方法添加到配置。Add to the configuration by calling the AddTables extension method.

  • Microsoft.Azure.Mobile.Server.Entity 使 Entity Framework 能够访问 SQL 数据库中的数据。Microsoft.Azure.Mobile.Server.Entity Enables the Entity Framework to access data in the SQL Database. 通过调用 AddTablesWithEntityFramework 扩展方法添加到配置。Add to the configuration by calling the AddTablesWithEntityFramework extension method.

  • Microsoft.Azure.Mobile.Server.Authentication 启用身份验证,并设置用于验证令牌的 OWIN 中间件。Microsoft.Azure.Mobile.Server.Authentication Enables authentication and sets-up the OWIN middleware used to validate tokens. 通过调用 AddAppServiceAuthentication 与 IAppBuilder.UseAppServiceAuthentication 扩展方法添加到配置 。Add to the configuration by calling the AddAppServiceAuthentication and IAppBuilder.UseAppServiceAuthentication extension methods.

  • Microsoft.Azure.Mobile.Server.Notifications 启用推送通知并定义推送注册终结点。Microsoft.Azure.Mobile.Server.Notifications Enables push notifications and defines a push registration endpoint. 通过调用 AddPushNotifications 扩展方法添加到配置。Add to the configuration by calling the AddPushNotifications extension method.

  • Microsoft.Azure.Mobile.Server.CrossDomain 创建从移动应用向旧版 Web 浏览器提供数据的控制器。Microsoft.Azure.Mobile.Server.CrossDomain Creates a controller that serves data to legacy web browsers from your Mobile App. 通过调用 MapLegacyCrossDomainController 扩展方法添加到配置 。Add to the configuration by calling the MapLegacyCrossDomainController extension method.

  • Microsoft.Azure.Mobile.Server.Login 提供 AppServiceLoginHandler.CreateToken() 方法,该方法为在自定义身份验证方案下使用的静态方法。Microsoft.Azure.Mobile.Server.Login Provides the AppServiceLoginHandler.CreateToken() method, which is a static method used during custom authentication scenarios.

如何:发布服务器项目How to: Publish the server project

本部分说明如何从 Visual Studio 发布 .NET 后端项目。This section shows you how to publish your .NET backend project from Visual Studio. 还可以使用 Git 或该处可用的任何其他方法部署后端项目。You can also deploy your backend project using Git or any of the other methods available there.

  1. 在 Visual Studio 中,重新生成项目以还原 NuGet 包。In Visual Studio, rebuild the project to restore NuGet packages.

  2. 在“解决方案资源管理器”中,右键单击项目,然后单击“发布” 。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.

  3. 如果系统要求选择发布目标,请单击“Azure App Service” > “下一步” ,然后使用 Azure 凭据登录(如果需要)。If asked to select a publish target, click Azure App Service > Next, then (if needed) sign-in with your Azure credentials. Visual Studio 将直接从 Azure 下载并安全存储发布设置。Visual Studio downloads and securely stores your publish settings directly from Azure.

  4. 选择“订阅” ,从“视图” 中选择“资源类型” ,展开“移动应用” ,单击移动应用后端,然后单击“确定” 。Choose your Subscription, select Resource Type from View, expand Mobile App, and click your Mobile App backend, then click OK.

  5. 验证发布配置文件信息,然后单击“发布” 。Verify the publish profile information and click Publish.

    成功发布移动应用后端后,可以看到表示成功的登陆页面。When your Mobile App backend has published successfully, you see a landing page indicating success.

如何:定义表控制器How to: Define a table controller

定义表控制器,向移动客户端公开 SQL 表。Define a Table Controller to expose a SQL table to mobile clients. 配置表控制器需要三个步骤:Configuring a Table Controller requires three steps:

  1. 创建数据传输对象 (DTO) 类。Create a Data Transfer Object (DTO) class.
  2. 在 Mobile DbContext 类中配置表引用。Configure a table reference in the Mobile DbContext class.
  3. 创建表控制器。Create a table controller.

数据传输对象 (DTO) 是继承自 EntityData 的纯 C# 对象。A Data Transfer Object (DTO) is a plain C# object that inherits from EntityData. 例如:For example:

public class TodoItem : EntityData
{
    public string Text { get; set; }
    public bool Complete {get; set;}
}

DTO 用于定义 SQL 数据库内的表。The DTO is used to define the table within the SQL database. 要创建数据库项,请将 DbSet<> 属性添加到正在使用的 DbContext。To create the database entry, add a DbSet<> property to the DbContext you are using. 在 Azure 移动应用的默认项目模板中,DbContext 称为 Models\MobileServiceContext.csIn the default project template for Azure Mobile Apps, the DbContext is called Models\MobileServiceContext.cs:

public class MobileServiceContext : DbContext
{
    private const string connectionStringName = "Name=MS_TableConnectionString";

    public MobileServiceContext() : base(connectionStringName)
    {

    }

    public DbSet<TodoItem> TodoItems { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Add(
            new AttributeToColumnAnnotationConvention<TableColumnAttribute, string>(
                "ServiceColumnTable", (property, attributes) => attributes.Single().ColumnType.ToString()));
    }
}

如果安装了 Azure SDK,现在可以按照以下步骤创建模板表控制器:If you have the Azure SDK installed, you can now create a template table controller as follows:

  1. 右键单击“控制器”文件夹,然后选择“添加” > “控制器...” 。Right-click on the Controllers folder and select Add > Controller....
  2. 选择“Azure 移动应用表控制器” 选项,然后单击“添加” 。Select the Azure Mobile Apps Table Controller option, then click Add.
  3. 在“添加控制器”对话框中 :In the Add Controller dialog:
    • 在“模型类” 下拉框中,选择新的 DTO。In the Model class dropdown, select your new DTO.
    • 在“DbContext” 下拉框中,选择“移动服务 DbContext”类。In the DbContext dropdown, select the Mobile Service DbContext class.
    • 已为控制器创建名称。The Controller name is created for you.
  4. 单击“添加” 。Click Add.

快速入门服务器项目包含简单的 TodoItemController的示例。The quickstart server project contains an example for a simple TodoItemController.

如何:调整表分页大小How to: Adjust the table paging size

默认情况下,Azure 移动应用为每个请求返回 50 条记录。By default, Azure Mobile Apps returns 50 records per request. 分页可以确保客户端不会长时间占用其 UI 线程或服务器,从而提供良好的用户体验。Paging ensures that the client does not tie up their UI thread nor the server for too long, ensuring a good user experience. 若要更改表分页大小,可增大服务器端“允许的查询大小”和客户端页面大小。服务器端“允许的查询大小”可使用 EnableQuery 属性进行调整: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)]

确保 PageSize 大于或等于客户端请求的大小。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.

如何:定义自定义 API 控制器How to: Define a custom API controller

自定义 API 控制器通过公开终结点,向移动应用后端提供最基本的功能。The custom API controller provides the most basic functionality to your Mobile App backend by exposing an endpoint. 可以使用 [MobileAppController] 属性注册移动设备特定的 API 控制器。You can register a mobile-specific API controller using the [MobileAppController] attribute. MobileAppController 属性将注册路由、设置移动应用 JSON 序列化程序,并打开客户端版本检查The MobileAppController attribute registers the route, sets up the Mobile Apps JSON serializer, and turns on client version checking.

  1. 在 Visual Studio 中,右键单击“控制器”文件夹,单击“添加” > “控制器” ,选择“Web API 2 控制器 — 空白” ,然后单击“添加” 。In Visual Studio, right-click the Controllers folder, then click Add > Controller, select Web API 2 Controller—Empty and click Add.

  2. 提供“控制器名称” (例如 CustomController),然后单击“添加” 。Supply a Controller name, such as CustomController, and click Add.

  3. 在新控制器类文件中添加以下 using 语句:In the new controller class file, add the following using statement:

    using Microsoft.Azure.Mobile.Server.Config;
    
  4. 将 [MobileAppController] 属性应用到 API 控制器类定义,如以下示例所示:Apply the [MobileAppController] attribute to the API controller class definition, as in the following example:

    [MobileAppController]
    public class CustomController : ApiController
    {
          //...
    }
    
  5. 在 App_Start/Startup.MobileApp.cs 文件中添加对 MapApiControllers 扩展方法的调用,如以下示例所示: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);
    

还可使用 UseDefaultConfiguration() 扩展方法代替 MapApiControllers()You can also use the UseDefaultConfiguration() extension method instead of MapApiControllers(). 客户端仍可访问任何未应用 MobileAppControllerAttribute 的控制器,但是使用任何移动应用客户端 SDK 的客户端可能无法正常使用此类控制器。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: Work with authentication

Azure 移动应用使用应用服务身份验证/授权来保护移动后端。Azure Mobile Apps uses App Service Authentication / Authorization to secure your mobile backend. 本部分说明如何在 .NET 后端服务器项目中执行以下身份验证相关的任务:This section shows you how to perform the following authentication-related tasks in your .NET backend server project:

如何:将身份验证添加到服务器项目How to: Add authentication to a server project

可以通过扩展 MobileAppConfiguration 对象并配置 OWIN 中间件,将身份验证添加到服务器项目。You can add authentication to your server project by extending the MobileAppConfiguration object and configuring OWIN middleware. 安装 Microsoft.Azure.Mobile.Server.Quickstart 包和调用 UseDefaultConfiguration 扩展方法时,可以跳到步骤 3。When you install the Microsoft.Azure.Mobile.Server.Quickstart package and call the UseDefaultConfiguration extension method, you can skip to step 3.

  1. 在 Visual Studio 中,安装 Microsoft.Azure.Mobile.Server.Authentication 包。In Visual Studio, install the Microsoft.Azure.Mobile.Server.Authentication package.

  2. 在 Startup.cs 项目文件中 Configuration 方法的开头添加以下代码行:In the Startup.cs project file, add the following line of code at the beginning of the Configuration method:

    app.UseAppServiceAuthentication(config);
    

    此 OWIN 中间件组件验证由关联的应用服务网关颁发的令牌。This OWIN middleware component validates tokens issued by the associated App Service gateway.

  3. [Authorize] 属性添加到任何要求身份验证的控制器或方法。Add the [Authorize] attribute to any controller or method that requires authentication.

要了解如何在移动应用后端对客户端进行身份验证,请参阅 Add authentication to your app(将身份验证添加到应用)。To learn about how to authenticate clients to your Mobile Apps backend, see Add authentication to your app.

如何:对应用程序使用自定义身份验证How to: Use custom authentication for your application

Important

若要启用自定义身份验证,必须先启用应用服务身份验证,而不必在 Azure 门户中为应用服务选择提供程序。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. 托管时这将启用 WEBSITE_AUTH_SIGNING_KEY 环境变量。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. 安装 Microsoft.Azure.Mobile.Server.Login 包有助于生成身份验证令牌。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. 在以下示例中,isValidAssertion() 方法(在其他位置定义)负责这些检查。In the example below, the isValidAssertion() method (defined elsewhere) is responsible for these checks.

通过创建 ApiController 并公开 registerlogin 操作,可以公开自定义身份验证。The custom authentication is exposed by creating an ApiController and exposing register and login actions. 客户端应使用自定义 UI 从用户处收集信息。The client should use a custom UI to collect the information from the user. 这些信息随后使用标准 HTTP POST 调用提交至 API。The information is then submitted to the API with a standard HTTP POST call. 服务器验证断言后,便可以使用 AppServiceLoginHandler.CreateToken() 方法颁发令牌。Once the server validates the assertion, a token is issued using the AppServiceLoginHandler.CreateToken() method. ApiController 不可 使用 [MobileAppController] 属性。The ApiController should not use the [MobileAppController] attribute.

示例 login 操作:An example login action:

    public IHttpActionResult Post([FromBody] JObject assertion)
    {
        if (isValidAssertion(assertion)) // user-defined function, checks against a database
        {
            JwtSecurityToken token = AppServiceLoginHandler.CreateToken(new Claim[] { new Claim(JwtRegisteredClaimNames.Sub, assertion["username"]) },
                mySigningKey,
                myAppURL,
                myAppURL,
                TimeSpan.FromHours(24) );
            return Ok(new LoginResult()
            {
                AuthenticationToken = token.RawData,
                User = new LoginResultUser() { UserId = userName.ToString() }
            });
        }
        else // user assertion was not valid
        {
            return this.Request.CreateUnauthorizedResponse();
        }
    }

在上述示例中,LoginResult 和 LoginResultUser 是公开必需属性的可序列化对象。In the preceding example, LoginResult and LoginResultUser are serializable objects exposing required properties. 客户端预期收到采用以下格式的 JSON 对象的登录响应:The client expects login responses to be returned as JSON objects of the form:

    {
        "authenticationToken": "<token>",
        "user": {
            "userId": "<userId>"
        }
    }

AppServiceLoginHandler.CreateToken() 方法包含 audience 和 issuer 参数。The AppServiceLoginHandler.CreateToken() method includes an audience and an issuer parameter. 这两个参数使用 HTTPS 方案设置为应用程序根目录的 URL。Both of these parameters are set to the URL of your application root, using the HTTPS scheme. 同样,应该将 secretKey 设置为应用程序的签名密钥值。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. 在应用服务中托管时,可以通过引用 WEBSITE_AUTH_SIGNING_KEY 环境变量获取签名密钥。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. 颁发的令牌必须至少包含一个使用者 (sub ) 声明。Minimally, the issued token must include a subject (sub) claim.

可通过重载身份验证路由支持标准客户端 loginAsync() 方法。You can support the standard client loginAsync() method by overloading the authentication route. 如果客户端通过调用 client.loginAsync('custom'); 进行登录,则路由必须是 /.auth/login/customIf the client calls client.loginAsync('custom'); to log in, your route must be /.auth/login/custom. 可使用 MapHttpRoute()设置用于自定义身份验证控制器的路由:You can set the route for the custom authentication controller using MapHttpRoute():

config.Routes.MapHttpRoute("custom", ".auth/login/custom", new { controller = "CustomAuth" });

Tip

使用 loginAsync() 方法可确保将身份验证令牌附加到后续对服务的所有调用。Using the loginAsync() approach ensures that the authentication token is attached to every subsequent call to the service.

如何:检索经过身份验证的用户信息How to: Retrieve authenticated user information

当应用服务对用户进行身份验证时,可以访问分配的用户 ID 和 .NET 后端代码中的其他信息。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. 以下代码可获取与请求关联的用户 ID: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;

SID 派生自提供程序特定的用户 ID,对于给定的用户和登录提供程序而言是静态的。The SID is derived from the provider-specific user ID and is static for a given user and login provider. 对于无效的身份验证令牌,SID 为 null。The SID is null for invalid authentication tokens.

应用服务还允许向登录提供程序请求特定声明。App Service also lets you request specific claims from your login provider. 每个标识提供者可使用标识提供者 SDK 提供详细信息。Each identity provider can provide more information using the identity provider SDK.可以在 Azure 门户的提供程序边栏选项卡中指定请求的声明。You can specify claims that are requested in the provider blade in the Azure portal. 某些声明需要对标识提供者进行其他配置。Some claims require additional configuration with the identity provider.

如何:限制已获授权用户的数据访问How to: Restrict data access for authorized users

上一部分已说明如何检索经过身份验证的用户的用户 ID。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. 例如,将 userId 列添加到表以及根据用户 ID 筛选查询结果,是将返回的数据局限于已获授权用户的简单方式。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. 以下代码只会在 SID 与 TodoItem 表上 UserId 列中的值匹配时才返回数据行: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);

Query() 方法返回的 IQueryable 可通过 LINQ 操作来处理筛选。The Query() method returns an IQueryable that can be manipulated by LINQ to handle filtering.

如何:将推送通知添加到服务器项目How to: Add push notifications to a server project

通过扩展 MobileAppConfiguration 对象并创建通知中心客户端,将推送通知添加到服务器项目。Add push notifications to your server project by extending the MobileAppConfiguration object and creating a Notification Hubs client.

  1. 在 Visual Studio 中,右键单击服务器项目并单击“管理 NuGet 包” ,搜索 Microsoft.Azure.Mobile.Server.Notifications,然后单击“安装” 。In Visual Studio, right-click the server project and click Manage NuGet Packages, search for Microsoft.Azure.Mobile.Server.Notifications, then click Install.

  2. 重复此步骤安装 Microsoft.Azure.NotificationHubs 包,其中包含通知中心客户端库。Repeat this step to install the Microsoft.Azure.NotificationHubs package, which includes the Notification Hubs client library.

  3. 在 App_Start/Startup.MobileApp.cs 中,在初始化期间添加对 AddPushNotifications 扩展方法的调用:In App_Start/Startup.MobileApp.cs, and add a call to the AddPushNotifications() extension method during initialization:

    new MobileAppConfiguration()
        // other features...
        .AddPushNotifications()
        .ApplyTo(config);
    
  4. 添加以下代码用于创建通知中心客户端:Add the following code that creates a Notification Hubs client:

    // Get the settings for the server project.
    HttpConfiguration config = this.Configuration;
    MobileAppSettingsDictionary settings =
        config.GetMobileAppSettingsProvider().GetMobileAppSettings();
    
    // Get the Notification Hubs credentials for the Mobile App.
    string notificationHubName = settings.NotificationHubName;
    string notificationHubConnection = settings
        .Connections[MobileAppSettingsKeys.NotificationHubConnectionString].ConnectionString;
    
    // Create a new Notification Hub client.
    NotificationHubClient hub = NotificationHubClient
    .CreateClientFromConnectionString(notificationHubConnection, notificationHubName);
    

现在可以使用通知中心客户端将推送通知发送到已注册的设备。You can now use the Notification Hubs client to send push notifications to registered devices. 有关详细信息,请参阅向应用添加推送通知For more information, see Add push notifications to your app. 若要了解通知中心的详细信息,请参阅通知中心概述To learn more about Notification Hubs, see Notification Hubs Overview.

如何:使用标记启用目标推送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:

  • 安装 ID 标识特定设备。The Installation ID identifies a specific device.
  • 基于经过身份验证的 SID 的用户 ID 可标识特定用户。The User Id based on the authenticated SID identifies a specific user.

可以从 MobileServiceClient 上的 installationId 属性访问安装 ID 。The installation ID can be accessed from the installationId property on the MobileServiceClient. 以下示例演示如何在通知中心内使用安装 ID 将标记添加到特定的安装:The following example shows how to use an installation ID to add a tag to a specific installation in Notification Hubs:

hub.PatchInstallation("my-installation-id", new[]
{
    new PartialUpdateOperation
    {
        Operation = UpdateOperationType.Add,
        Path = "/tags",
        Value = "{my-tag}"
    }
});

创建安装时,后端会忽略客户端在推送通知注册期间提供的任何标记。Any tags supplied by the client during push notification registration are ignored by the backend when creating the installation. 要使客户端能够将标记添加到安装,必须创建使用上述模式添加标记的自定义 API。To enable a client to add tags to the installation, you must create a custom API that adds tags using the preceding pattern.

有关示例,请参阅应用服务移动应用已完成的快速入门示例中的 客户端添加的推送通知标记See Client-added push notification tags in the App Service Mobile Apps completed quickstart sample for an example.

如何:将推送通知发送到经过身份验证的用户How to: Send push notifications to an authenticated user

当经过身份验证的用户注册推送通知时,用户 ID 标记自动添加到注册中。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. 以下代码获取发出请求的用户的 SID,并将模板推送通知发送到该用户的每个设备注册:The following code gets the SID of user making the request and sends a template push notification to every device registration for that person:

// Get the current user SID and create a tag for the current user.
var claimsPrincipal = this.User as ClaimsPrincipal;
string sid = claimsPrincipal.FindFirst(ClaimTypes.NameIdentifier).Value;
string userTag = "_UserId:" + sid;

// Build a dictionary for the template with the item message text.
var notification = new Dictionary<string, string> { { "message", item.Text } };

// Send a template notification to the user ID.
await hub.SendTemplateNotificationAsync(notification, userTag);

在注册来自经过身份验证客户端的推送通知时,请确保在尝试注册之前身份验证已完成。When registering for push notifications from an authenticated client, make sure that authentication is complete before attempting registration. 有关详细信息,请参阅适用于 .NET 后端的应用服务移动应用完整快速入门示例中的推送到用户For more information, see Push to users in the App Service Mobile Apps completed quickstart sample for .NET backend.

如何:对 .NET 服务器 SDK 进行调试和故障排除How to: Debug and troubleshoot the .NET Server SDK

Azure 应用服务提供多种适用于 ASP.NET 应用程序的调试和故障排除方法:Azure App Service provides several debugging and troubleshooting techniques for ASP.NET applications:

日志记录Logging

可以使用标准的 ASP.NET 跟踪写入来写入应用服务诊断日志。You can write to App Service diagnostic logs by using the standard ASP.NET trace writing. 写入日志之前,必须在移动应用后端中启用诊断。Before you can write to the logs, you must enable diagnostics in your Mobile App backend.

启用诊断并写入日志:To enable diagnostics and write to the logs:

  1. 遵循如何启用诊断中的步骤。Follow the steps in How to enable diagnostics.

  2. 在代码文件中添加以下 using 语句:Add the following using statement in your code file:

    using System.Web.Http.Tracing;
    
  3. 创建跟踪写入器以便从 .NET 后端写入诊断日志,如下所示:Create a trace writer to write from the .NET backend to the diagnostic logs, as follows:

    ITraceWriter traceWriter = this.Configuration.Services.GetTraceWriter();
    traceWriter.Info("Hello, World");
    
  4. 重新发布服务器项目,并访问移动应用后端,结合日志记录执行代码路径。Republish your server project, and access the Mobile App backend to execute the code path with the logging.

  5. 根据如何:下载日志中所述下载并评估日志。Download and evaluate the logs, as described in How to: Download logs.

使用身份验证进行本地调试Local debugging with authentication

可以先在本地运行应用程序以测试更改,然后将更改发布到云中。You can run your application locally to test changes before publishing them to the cloud. 对于大部分 Azure 移动应用后端,在 Visual Studio 中按 F5For 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.

确保移动后端中已安装 Microsoft.Azure.Mobile.Server.AuthenticationEnsure that your mobile backend has Microsoft.Azure.Mobile.Server.Authentication installed. 然后,在将 MobileAppConfiguration 应用到 HttpConfiguration 之后,在应用程序的 OWIN 启动类中添加以下代码:Then, in your application's OWIN startup class, add the following, after MobileAppConfiguration has been applied to your HttpConfiguration:

    app.UseAppServiceAuthentication(new AppServiceAuthenticationOptions()
    {
        SigningKey = ConfigurationManager.AppSettings["authSigningKey"],
        ValidAudiences = new[] { ConfigurationManager.AppSettings["authAudience"] },
        ValidIssuers = new[] { ConfigurationManager.AppSettings["authIssuer"] },
        TokenHandler = config.GetAppServiceTokenHandler()
    });

在上例中,应使用 HTTPS 方案将 Web.config 文件中的 authAudience 和 authIssuer 应用程序设置配置为每个应用程序根目录的 URL 。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. 同样,应将 authSigningKey 设置为应用程序的签名密钥值。Similarly you should set authSigningKey to be the value of your application's signing key. 获取签名密钥:To obtain the signing key:

  1. Azure 门户Navigate to your app within the Azure portal
  2. 依次单击“工具” 、“Kudu” 、“转到” 。Click Tools, Kudu, Go.
  3. 在 Kudu 管理站点中,单击“环境” 。In the Kudu Management site, click Environment.
  4. 查找 WEBSITE_AUTH_SIGNING_KEY 的值。Find the value for WEBSITE_AUTH_SIGNING_KEY.

使用本地应用程序配置中 authSigningKey 参数的签名密钥。移动后端现已经过相关配置,在本地运行时可以验证令牌,该令牌由客户端从基于云的终结点获取。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.