12
OVERVIEWgit
CREATING AND USING ODATA SERVICES
USING AZURE FUNCTIONS
SUMMARYgithub
Web API目标是使一种通讯技术很是灵活并知足全部需求。WCF最初基于SOAP(简单对象访问协议)。现在,咱们有许多场景,不须要强大的SOAP加强功能。 对于更简单的场景,例如返回JSON的HTTP请求,WCF太复杂了。
Web API提供基于Representational State Transfer(REST)的简单通讯技术。REST是一种基于某些约束的架构风格。 比较基于REST架构风格的服务与使用SOAP的服务的不一样。
相同:数据库
不一样:json
This chapter takes you through a journey that covers various important aspects of the Web API using ASP.NET Core MVC—creating a service, using different routing methods, creating a client, using OData, securing the service, and using custom hosts. The chapter shows you how you can take the same services created for hosting with ASP.NET Core and use them from Microsoft Azure Functions, which is another option to create a Web API with C# and .NET.api
本章将向您介绍使用ASP.NET Core MVC建立服务,使用不一样路由方法,建立客户端,使用OData,保护服务和使用自定义主机的Web API的各个重要方面的旅程。 本章向您展现了如何使用ASP.NET Core为托管建立的相同服务,并从Microsoft Azure Functions中使用它们,这是使用C#和.NET建立Web API的另外一种选择。服务器
使用默认模板建立WebApi。架构
`在较大的应用程序中,建议分离为多个库。
若是您建立包含services和models的库,则能够轻松地使用来自不一样技术的相同类型(例如,Web API项目以及Azure Functions)。
Web Api 的实现(控制器——controller)也能够从宿主应用程序单独分离出来。`mvc
定义服务接口
代码: IBookChaptersService.cs(sync部分)异步
定义服务,用于检索,添加和更新书籍章节。
代码: BookChaptersService.cs(sync部分)
建立SampleChapters,用来填充数据。
代码: SampleChapters.cs
在宿主应用程序中,使用DI注册服务。
代码: Startup.cs
public void ConfigureServices(IServiceCollection services) { IMvcBuilder mvcBuilder = services.AddMvc(); mvcBuilder.SetCompatibilityVersion(CompatibilityVersion.Version_2_1); #region 改变响应格式 mvcBuilder.AddXmlSerializerFormatters(); #endregion #region 注册服务 // BookChaptersService做为单例注册,因此能够同时从多个线程访问它; // 这就是为何在实现中须要ConcurrentDictionary的缘由 services.AddSingleton<IBookChaptersService, BookChaptersService>(); services.AddSingleton<SampleChapters>(); #endregion }
调用SampleChapters,以便检索。
代码: Startup.cs
public void Configure(IApplicationBuilder app, IHostingEnvironment env,SampleChapters sampleChapters) { //.. sampleChapters.CreateSampleChapters(); }
运行效果
返回XML——配置以下:
//改变响应格式 [Produces("application/json","application/xml")] [Route("api/[controller]")] // [ApiController] public class BookChaptersController : Controller { }
public void ConfigureServices(IServiceCollection services) { IMvcBuilder mvcBuilder = services.AddMvc(); mvcBuilder.SetCompatibilityVersion(CompatibilityVersion.Version_2_1); #region 改变响应格式 mvcBuilder.AddXmlSerializerFormatters(); #endregion #region 注册服务 // BookChaptersService做为单例注册,因此能够同时从多个线程访问它; // 这就是为何在实现中须要ConcurrentDictionary的缘由 services.AddSingleton<IBookChaptersService, BookChaptersService>(); services.AddSingleton<SampleChapters>(); #endregion }
HTTP方法返回的结果:
Http Method | Description | Request Body | Response Body |
---|---|---|---|
GET | 返回资源 | Empty | The resource |
POST | 增长资源 | The resource to add | The resource |
PUT | 更新资源 | The resource to update | None |
DELETE | 删除资源 | Empty | Empty |
下表显示了重要的HTTP状态代码 。Controller方法返回的实例化对象(带有状态代码)。若是想返回任意的HTTP状态代码,能够返回一个HttpStatusCodeResult对象,该对象能够使用本身须要的状态代码进行初始化:
Http Status Code | Controller Method | Type |
---|---|---|
200 OK | Ok | OkResult |
201 Created | CreatedAtRoute | CreatedAtRouteResult |
204 No Content | NoContent | NoContentResult |
400 Bad Request | BadRequest | BadRequestResult |
401 Unauthorized | Unauthorized | UnauthorizedResult |
404 Not Found | NotFound | NotFoundResult |
Any status code | StatusCodeResult |
因为许多技术(例如使用HttpClient类调用其余服务)仅提供异步方法。 因此会有异步服务。
定义服务接口
代码: IBookChaptersService.cs(async部分)
定义服务,用于检索,添加和更新书籍章节。
代码: BookChaptersService.cs(async部分)
BookChaptersService类实现异步方法。 从字典读取和写入时,不须要异步功能,所以Task使用FromResult方法建立返回值。
发送请求、从客户端接受数据。包括GET、POST、PUT、DELETE。
返回Json和xml格式的字符串。
建立UrlService——提供基地址与uri
代码: UrlService.cs
建立泛型类HttpClientService,以便为不一样的数据类型使用一个实现。
代码: HttpClientService.cs
建立Model——BookChapter
代码: BookChapter.cs
建立客户端类,进行对HttpClientService的调用
代码: SampleRequestClient.cs
注册服务、调用SampleRequestClient
代码: Program.cs
建立DbContext
代码: DbContext.cs
建立DBBookChaptersService代替BookChaptersService
代码: DBBookChaptersService.cs
注册服务——配置ConfigureServices
代码: Startup.cs
配置链接字符串
代码: appsettings.json
添加NuGet——Swashbuckle.AspNetCore
public void ConfigureServices(IServiceCollection services) { // ... // OpenAPI services.AddSwaggerGen(options => { //options.DescribeAllEnumsAsStrings(); options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info { Title = "Azure Adapter Api - Catalog HTTP API", Version = "v1", Description = "The Catalog Microservice HTTP API. This is a Data-Driven/CRUD microservice sample", TermsOfService = "Terms Of Service" }); }); //... }
public void Configure(IApplicationBuilder app, IHostingEnvironment env,SampleChapters sampleChapters) { // ... // OpenAPI app.UseSwagger().UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1"); }); }
定义Model—Book、BookChapter
定义DBContext—BooksContext
定义Service—CreateBooksService