首页 > 解决方案 > API 将数据库链接到 MVC 项目和移动应用 Xamarin

问题描述

我是 Xamarin 的新手,我正在使用带有最新 Xamarin 更新的 VS 2017 Enterprise。

我想添加一个 API,以便 Db 可以与我的移动应用程序和 MVC 项目进行通信。

我创建了一个跨平台的空白 .NET Standard 项目。

我在解决方案中添加了一个新文件夹,并在该文件夹中添加了一个类来编写我的 RestAPI 代码。

编写代码时我使用了 HttpClient 但它给了我一个错误,询问我是否

缺少程序集或参考。

如果我不能使用 HttpClient,如何为我的 REstApi 编写代码?

或者有没有更好的方法让我的 Db 与我的 MVC 项目和移动应用程序进行通信?

我将在 Azure 上发布我的 MVC 项目和移动应用程序。谢谢

标签: apiazuremodel-view-controllerxamarin.formsvisual-studio-2017

解决方案


首先

对于出现的错误: missing an assembly or reference.

HttpClient 位于“System.Net.Http”命名空间中。

您需要添加:using System.Net.Http;

正如这里提到的


其次

有没有更好的方法让您的 Db 与您的MVC 项目移动应用程序进行通信?

的,有更好的方法,在发布你的 MVC 项目之后,

您可以使用Azure 移动客户端

  • 步骤1

打开“包管理器控制台”并输入

安装包 Microsoft.Azure.Mobile.Client -版本 4.0.2

或者您可以从Azure 移动客户端 SDK获取最新版本

此库提供用于创建连接到 Azure 移动应用的 Windows 和 Xamarin 移动应用的功能

  • 第2步

假设您有一个名为“user”的类,并且您想要读取、插入、更新和删除数据

看看下面的代码示例:

using Microsoft.WindowsAzure.MobileServices;
using System.Collections.ObjectModel;
using System.Threading.Tasks;

 public class User {/*....*/ }


  public class AzureServices
  {
      private static readonly string url = "http://xxxxx.azurewebsites.net";

      /*
       * The Azure Mobile Client SDK provides the MobileServiceClient class, 
       * which is used by a Xamarin.Forms application to access the Azure Mobile Apps instance
      */

      public MobileServiceClient Client;
      public IMobileServiceTable<User> UserTable;

      public AzureServices()
      {
          /* 
           * When the MobileServiceClient instance is created,
           * an application URL must be specified to identify the Azure Mobile Apps instance.
          */

          Client = new MobileServiceClient(url);

          //calling the GetTable method on the MobileServiceClient instance, which returns a IMobileServiceTable<User> reference.
          UserTable = Client.GetTable<User>();
      }

      // Querying Data
      public async Task<ObservableCollection<User>> GetAllUsers(bool sync = false)
      {
          var userList = await UserTable.ToEnumerableAsync();
          return new ObservableCollection<User>(userList);
      }
      //Inserting Data
      public async Task AddUser(User item)
      {
          await UserTable.InsertAsync(item);
      }
      // Updating Data
      public async Task UpdateUser(User item)
      {
          await UserTable.UpdateAsync(item);
      }
      // Deleting Data
      public async Task DeleteUser(User item)
      {
          await UserTable.DeleteAsync(item);
      }

  }

有关详细信息,请访问Azure 移动应用


推荐阅读