ASP.NET Core, WEB API 和 Repository 类






2.73/5 (8投票s)
在本文中,我们将详细了解如何在 WEB API 中使用 Repository 模式创建 ASP.NET Core。
引言
本文展示了如何在 WEB API 中使用 Repository 模式创建 ASP.NET Core。
WEB API
Web API 是一种为浏览器和移动设备构建 HTTP 服务的简单易用的方法。 它有以下四种方法:Get/Post/Put 和 Delete,其中
- Get用于请求数据。 (- Select)
- Post用于创建数据。 (- Insert)
- Put用于更新数据。
- Delete用于删除数据。
Repository 类
Repository 模式允许我们为业务逻辑和数据库操作创建一个新的层。 我们可以使用 repository 来存储我们的数据。 要了解更多关于 repository 的信息,请查看此链接。
必备组件
Using the Code
步骤 1:创建我们的 ASP.NET Core 1.0.1 Web 应用程序
安装 Visual Studio 2015 和 ASP.NET Core 1.0.1 后,单击“开始”,然后单击“程序”,并选择“Visual Studio 2015” - 单击“Visual Studio 2015”。 单击“新建”,然后单击“项目”,选择“Web”,然后选择“ASP.NET Core Web 应用程序”。 输入你的项目名称,然后单击“确定”。

接下来选择“WEB API”。 单击“确定”。

步骤 2:创建模块
要首先创建我们的模块类,我们在解决方案项目中创建一个文件夹。
右键单击我们的解决方案 > 单击“添加” > 单击“新建文件夹”

将文件夹命名为Models。

创建模型类
右键单击 Model 文件夹,添加新类并将其命名为“StudentMasters.cs”。
在此类中,我们声明我们的属性变量。
namespace ASPNETCOREWEBAPI.Models
{
    public class StudentMasters
    {
        public string StdName { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
        public string Address { get; set; }
    }
}
步骤 3:Repository 类
创建 Repository 类
在这里,我们创建一个 Repository 类来注入到我们的控制器中。 要创建一个 Repository 类
右键单击 Models 文件夹,然后单击“添加类”。
将类命名为 IStudentRepository。
在这里,我们可以看到我给定的类名以 I 开头,因为这个类我们将用作接口,在这里我们将只声明在我们的 StudentRepository 类中使用的方法。
public interface IStudentRepository
    {
        IEnumerable<StudentMasters> GetAll();
        void Add(StudentMasters info);
    }
在这个接口中,我们只添加了 Get 和 Add 方法。 在我们的下一篇文章中,我们将详细介绍 CRUD 操作。
创建一个类来实现接口
现在我们在 Models 文件夹中创建另一个类,命名为“StudentRepository”。
在此类中,我们创建方法来获取所有 student 信息并添加 student 信息。
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ASPNETCOREWEBAPI.Models
{
    public class StudentRepository: IStudentRepository
    {
        private static ConcurrentDictionary<string, StudentMasters> 
                stdMaster = new ConcurrentDictionary<string, StudentMasters>();
        public StudentRepository()
        {
            Add(new StudentMasters
            {
                StdName = "Shanu",
                Phone = "+821039120700",
                Email = "syedshanumcain@gmail.com",
                Address = "Seoul,Korea"
            });
        }
        public IEnumerable<StudentMasters> GetAll()
        {
            return stdMaster.Values;
        }
        public void Add(StudentMasters studentInfo)
        {
            stdMaster[studentInfo.StdName] = studentInfo;
        }
    }
在配置服务中添加 Repository 类
为了将我们的 repository 注入到控制器中,我们需要使用依赖注入容器注册 repository 类。
要了解什么是依赖注入 (DI),请查看此链接。
从我们的解决方案项目中打开 Startup.cs 文件

首先,我们添加 using 以导入我们的 Models 文件夹
using ASPNETCOREWEBAPI.Models;
接下来,我们注册我们自己的服务,如下面的代码
services.AddSingleton<IStudentRepository, StudentRepository>();
这样的内容。
// This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // Add framework services.
            services.AddMvc();
            services.AddSingleton<IStudentRepository, StudentRepository>();
        }
这是完整的 Startup.cs 类

步骤 4:创建控制器
右键单击 Controllers 文件夹 > 单击“添加” > 单击“新建项”。

从左侧选择“ASP.NET”> 选择“Web API 控制器类”。
将你的控制器命名为“StudentController.cs”。
默认情况下,我们的 Controller 类将如下所示
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling Web API for empty projects, 
// visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace ASPNETCOREWEBAPI.Controllers
{
    [Route("api/[controller]")]
    public class StudentController : Controller
    {
        // GET: api/values
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }
        // GET api/values/5
        [HttpGet("{id}")]
        public string Get(int id)
        {
            return "value";
        }
        // POST api/values
        [HttpPost]
        public void Post([FromBody]string value)
        {
        }
        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody]string value)
        {
        }
        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}
删除我们控制器中的所有默认方法,并进行更改以添加我们的代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling Web API for empty projects, 
// visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace ASPNETCOREWEBAPI.Controllers
{
    [Route("api/[controller]")]
    public class StudentController : Controller
    {
}
首先,我们在我们的 controller 类中添加 using
using ASPNETCOREWEBAPI.Models;
接下来,我们将为我们的 Models 创建对象。
[Route("api/[controller]")]
    public class StudentController : Controller
    {
        private List<StudentMasters> _stdInfo;
}
添加示例信息
接下来,我们添加一些示例 student 信息,以便从我们的 WEB API 方法中获取。
[Route("api/[controller]")]
    public class StudentController : Controller
    {
        private List<StudentMasters> _stdInfo;
        public StudentController()
        {
            InitializeData();
        }
//To bind initial Student Information
        private void InitializeData()
        {
            _stdInfo = new List<StudentMasters>();
            var studentInfo1 = new StudentMasters
            {
                StdName = "Shanu",
                Phone = "+821039120700",
                Email = "syedshanumcain@gmail.com",
                Address = "Seoul,Korea"
            };
            var studentInfo2 = new StudentMasters
            {
                StdName = "Afraz",
                Phone = "+821000000700",
                Email = "afraz@gmail.com",
                Address = "Madurai,India"
            };
            var studentInfo3 = new StudentMasters
            {
                StdName = "Afreen",
                Phone = "+821012340700",
                Email = "afreen@gmail.com",
                Address = "Chennai,India"
            };
            _stdInfo.Add(studentInfo1);
            _stdInfo.Add(studentInfo2);
            _stdInfo.Add(studentInfo3);
        }
}
WEB API Get 方法
使用此 get 方法,我们返回所有 student 信息作为 JSON 结果。
[Route("api/[controller]")]
    public class StudentController : Controller
    {
        private List<StudentMasters> _stdInfo;
        public StudentController()
        {
            InitializeData();
        }
        //This will return all Student Information
        [HttpGet]
        public IEnumerable<StudentMasters> GetAll()
        {
            return _stdInfo;
        }
}
这是我们的 controller 类的完整代码,包括添加示例数据和使用 WEB API Get 方法。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using ASPNETCOREWEBAPI.Models;
// For more information on enabling Web API for empty projects, 
// visit http://go.microsoft.com/fwlink/?LinkID=397860
namespace ASPNETCOREWEBAPI.Controllers
{
    [Route("api/[controller]")]
    public class StudentController : Controller
    {
        private List<StudentMasters> _stdInfo;
        public StudentController()
        {
            InitializeData();
        }
        //This will return all Student Information
        [HttpGet]
        public IEnumerable<StudentMasters> GetAll()
        {
            return _stdInfo;
        }
        //To bind initial Student Information
        private void InitializeData()
        {
            _stdInfo = new List<StudentMasters>();
            var studentInfo1 = new StudentMasters
            {
                StdName = "Shanu",
                Phone = "+821039120700",
                Email = "syedshanumcain@gmail.com",
                Address = "Seoul,Korea"
            };
            var studentInfo2 = new StudentMasters
            {
                StdName = "Afraz",
                Phone = "+821000000700",
                Email = "afraz@gmail.com",
                Address = "Madurai,India"
            };
            var studentInfo3 = new StudentMasters
            {
                StdName = "Afreen",
                Phone = "+821012340700",
                Email = "afreen@gmail.com",
                Address = "Chennai,India"
            };
            _stdInfo.Add(studentInfo1);
            _stdInfo.Add(studentInfo2);
            _stdInfo.Add(studentInfo3);
        }
    }
}
步骤 5:运行应用程序
要查看结果,请运行应用程序。
当我们运行应用程序时,默认情况下,我们可以看到 values 控制器结果作为 values https://:64764/api/values

将 Values 更改为我们新创建的控制器名称 student “https://:64764/api/student“。
在这里,现在我们可以看到我们添加的所有 student 信息都已显示为 JSON 结果。

历史
- 2016 年 11 月 17 日:初始版本


