上一篇写的是使用静态基类方法的实现步骤:  http://www.cnblogs.com/cgzl/p/8726805.html

使用dynamic (ExpandoObject)的好处就是可以动态组建返回类型, 之前使用的是ViewModel, 如果想返回结果的话, 肯定需要把ViewModel所有的属性都返回, 如果属性比较多, 就有可能造成性能和灵活性等问题. 而使用ExpandoObject(dynamic)就可以解决这个问题.

返回一个对象

返回一个dynamic类型的对象, 需要把所需要的属性从ViewModel抽取出来并转化成dynamic对象, 这里所需要的属性通常是从参数传进来的, 例如针对下面的CustomerViewModel类, 参数可能是这样的: "Name, Company":

using System;
using SalesApi.Core.Abstractions.DomainModels; namespace SalesApi.ViewModels
{
public class CustomerViewModel: EntityBase
{
public string Company { get; set; }
public string Name { get; set; }
public DateTimeOffset EstablishmentTime { get; set; }
}
}

还需要一个Extension Method可以把对象按照需要的属性转化成dynamic类型:

using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Reflection; namespace SalesApi.Shared.Helpers
{
public static class ObjectExtensions
{
public static ExpandoObject ToDynamic<TSource>(this TSource source, string fields = null)
{
if (source == null)
{
throw new ArgumentNullException("source");
} var dataShapedObject = new ExpandoObject();
if (string.IsNullOrWhiteSpace(fields))
{
// 所有的 public properties 应该包含在ExpandoObject里
var propertyInfos = typeof(TSource).GetProperties(BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
foreach (var propertyInfo in propertyInfos)
{
// 取得源对象上该property的值
var propertyValue = propertyInfo.GetValue(source);
// 为ExpandoObject添加field
((IDictionary<string, object>)dataShapedObject).Add(propertyInfo.Name, propertyValue);
}
return dataShapedObject;
} // field是使用 "," 分割的, 这里是进行分割动作.
var fieldsAfterSplit = fields.Split(',');
foreach (var field in fieldsAfterSplit)
{
var propertyName = field.Trim(); // 使用反射来获取源对象上的property
// 需要包括public和实例属性, 并忽略大小写.
var propertyInfo = typeof(TSource).GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
if (propertyInfo == null)
{
throw new Exception($"没有在‘{typeof(TSource)}’上找到‘{propertyName}’这个Property");
} // 取得源对象property的值
var propertyValue = propertyInfo.GetValue(source);
// 为ExpandoObject添加field
((IDictionary<string, object>)dataShapedObject).Add(propertyInfo.Name, propertyValue);
} return dataShapedObject;
}
}
}

注意: 这里的逻辑是如果没有选择需要的属性的话, 那么就返回所有合适的属性.

然后在CustomerController里面:

首先创建为对象添加link的方法:

        private IEnumerable<LinkViewModel> CreateLinksForCustomer(int id, string fields = null)
{
var links = new List<LinkViewModel>();
if (string.IsNullOrWhiteSpace(fields))
{
links.Add(
new LinkViewModel(_urlHelper.Link("GetCustomer", new { id = id }),
"self",
"GET"));
}
else
{
links.Add(
new LinkViewModel(_urlHelper.Link("GetCustomer", new { id = id, fields = fields }),
"self",
"GET"));
} links.Add(
new LinkViewModel(_urlHelper.Link("DeleteCustomer", new { id = id }),
"delete_customer",
"DELETE")); links.Add(
new LinkViewModel(_urlHelper.Link("CreateCustomer", new { id = id }),
"create_customer",
"POST")); return links;
}

针对返回一个对象, 添加了本身的连接, 添加的连接 以及 删除的连接.

然后修改Get和Post的Action:

        [HttpGet]
[Route("{id}", Name = "GetCustomer")]
public async Task<IActionResult> Get(int id, string fields)
{
var item = await _customerRepository.GetSingleAsync(id);
if (item == null)
{
return NotFound();
}
var customerVm = Mapper.Map<CustomerViewModel>(item);
var links = CreateLinksForCustomer(id, fields);
var dynamicObject = customerVm.ToDynamic(fields) as IDictionary<string, object>;
dynamicObject.Add("links", links);
return Ok(dynamicObject);
} [HttpPost(Name = "CreateCustomer")]
public async Task<IActionResult> Post([FromBody] CustomerViewModel customerVm)
{
if (customerVm == null)
{
return BadRequest();
} if (!ModelState.IsValid)
{
return BadRequest(ModelState);
} var newItem = Mapper.Map<Customer>(customerVm);
_customerRepository.Add(newItem);
if (!await UnitOfWork.SaveAsync())
{
return StatusCode(, "保存时出错");
} var vm = Mapper.Map<CustomerViewModel>(newItem); var links = CreateLinksForCustomer(vm.Id);
var dynamicObject = vm.ToDynamic() as IDictionary<string, object>;
dynamicObject.Add("links", links);
return CreatedAtRoute("GetCustomer", new { id = dynamicObject["Id"] }, dynamicObject);
}

红色部分是相关的代码. 创建links之后把vm对象按照需要的属性转化成dynamic对象. 然后往这个dynamic对象里面添加links属性. 最后返回该对象.

下面测试一下.

POST:

结果:

由于POST方法里面没有选择任何fields, 所以返回所有的属性.

下面试一下GET:

再试一下GET, 选择几个fields:

OK, 效果都如预期.

但是有一个问题, 因为返回的json的Pascal case的(只有dynamic对象返回的是Pascal case, 其他ViewModel现在返回的都是camel case的), 而camel case才是更好的选择 .

所以在Startup里面可以这样设置:

            services.AddMvc(options =>
{
options.ReturnHttpNotAcceptable = true;
// the default formatter is the first one in the list.
options.OutputFormatters.Remove(new XmlDataContractSerializerOutputFormatter()); // set authorization on all controllers or routes
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
})
.AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
})
.AddFluetValidations();

然后再试试:

OK.

返回集合

首先编写创建links的方法:

        private IEnumerable<LinkViewModel> CreateLinksForCustomers(string fields = null)
{
var links = new List<LinkViewModel>();
if (string.IsNullOrWhiteSpace(fields))
{
links.Add(
new LinkViewModel(_urlHelper.Link("GetAllCustomers", new { fields = fields }),
"self",
"GET"));
}
else
{
links.Add(
new LinkViewModel(_urlHelper.Link("GetAllCustomers", new { }),
"self",
"GET"));
}
return links;
}

这个很简单.

然后需要针对IEnumerable<T>类型创建把ViewModel转化成dynamic对象的Extension方法:

using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Reflection; namespace SalesApi.Shared.Helpers
{
public static class IEnumerableExtensions
{
public static IEnumerable<ExpandoObject> ToDynamicIEnumerable<TSource>(this IEnumerable<TSource> source, string fields)
{
if (source == null)
{
throw new ArgumentNullException("source");
} var expandoObjectList = new List<ExpandoObject>();
var propertyInfoList = new List<PropertyInfo>();
if (string.IsNullOrWhiteSpace(fields))
{
var propertyInfos = typeof(TSource).GetProperties(BindingFlags.Public | BindingFlags.Instance);
propertyInfoList.AddRange(propertyInfos);
}
else
{
var fieldsAfterSplit = fields.Split(',');
foreach (var field in fieldsAfterSplit)
{
var propertyName = field.Trim();
var propertyInfo = typeof(TSource).GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
if (propertyInfo == null)
{
throw new Exception($"Property {propertyName} wasn't found on {typeof(TSource)}");
}
propertyInfoList.Add(propertyInfo);
}
} foreach (TSource sourceObject in source)
{
var dataShapedObject = new ExpandoObject();
foreach (var propertyInfo in propertyInfoList)
{
var propertyValue = propertyInfo.GetValue(sourceObject);
((IDictionary<string, object>)dataShapedObject).Add(propertyInfo.Name, propertyValue);
}
expandoObjectList.Add(dataShapedObject);
} return expandoObjectList;
}
}
}

注意: 反射的开销很大, 注意性能.

然后修改GetAll方法:

        [HttpGet(Name = "GetAllCustomers")]
public async Task<IActionResult> GetAll(string fields)
{
var items = await _customerRepository.GetAllAsync();
var results = Mapper.Map<IEnumerable<CustomerViewModel>>(items);
var dynamicList = results.ToDynamicIEnumerable(fields);
var links = CreateLinksForCustomers(fields);
var dynamicListWithLinks = dynamicList.Select(customer =>
{
var customerDictionary = customer as IDictionary<string, object>;
var customerLinks = CreateLinksForCustomer(
(int)customerDictionary["Id"], fields);
customerDictionary.Add("links", customerLinks);
return customerDictionary;
});
var resultWithLink = new {
Value = dynamicListWithLinks,
Links = links
};
return Ok(resultWithLink);
}

红色部分是相关代码.

测试一下:

不选择属性:

选择部分属性:

OK.

HATEOAS这部分就写到这.

其实 翻页的逻辑很适合使用HATEOAS结构. 有空我再写一个翻页的吧.

使用 dynamic 类型让 ASP.NET Core 实现 HATEOAS 结构的 RESTtful API的更多相关文章

  1. 使用 dynamic 类型让 ASP.NET Core 实现 HATEOAS 结构的 RESTful API

    上一篇写的是使用静态基类方法的实现步骤:  http://www.cnblogs.com/cgzl/p/8726805.html 使用dynamic (ExpandoObject)的好处就是可以动态组 ...

  2. 【ASP.NET Core】体验一下 Mini Web API

    在上一篇水文中,老周给大伙伴们简单演示了通过 Socket 编程的方式控制 MPD (在树莓派上).按照计划,老周还想给大伙伴们演示一下使用 Web API 来封装对 MPD 控制.思路很 Easy, ...

  3. 使用Http-Repl工具测试ASP.NET Core 2.2中的Web Api项目

    今天,Visual Studio中没有内置工具来测试WEB API.使用浏览器,只能测试http GET请求.您需要使用Postman,SoapUI,Fiddler或Swagger等第三方工具来执行W ...

  4. ASP.NET Core项目目录结构介绍

    我们下面通过在Visual Studio 2017中创建一个空的Web应用程序来详细说明下asp.net core项目目录结构: 1.项目结构说明 (1).依赖项 这里主要分两部分SDK, 目前这两部 ...

  5. ASP.NET Core 中文文档 第二章 指南(2)用 Visual Studio 和 ASP.NET Core MVC 创建首个 Web API

    原文:Building Your First Web API with ASP.NET Core MVC and Visual Studio 作者:Mike Wasson 和 Rick Anderso ...

  6. ASP.NET Core的身份认证框架IdentityServer4--(2)API跟WEB端配置

    API配置 可以使用ASP.NET Core Web API模板.同样,我们建议您控制端口并使用与之前一样的方法来配置Kestrel和启动配置文件.端口配置为http://localhost:5001 ...

  7. 为什么 web 开发人员需要迁移到. NET Core, 并使用 ASP.NET Core MVC 构建 web 和 webservice/API

    2018 .NET开发者调查报告: .NET Core 是怎么样的状态,这里我们看到了还有非常多的.net开发人员还在观望,本文给大家一个建议.这仅代表我的个人意见, 我有充分的理由推荐.net 程序 ...

  8. 在ASP.NET Core MVC中构建简单 Web Api

    Getting Started 在 ASP.NET Core MVC 框架中,ASP.NET 团队为我们提供了一整套的用于构建一个 Web 中的各种部分所需的套件,那么有些时候我们只需要做一个简单的 ...

  9. 在ASP.NET Core 2.2 中创建 Web API并结合Swagger

    一.创建 ASP.NET Core WebApi项目 二.添加 三. ----------------------------------------------------------- 一.创建项 ...

随机推荐

  1. webapi下的web请求

    先看webapi提供的服务: [HttpPost] public ResultBaseModel SiteList(SiteModel param) { ResultBaseModel resultM ...

  2. signalR的集群与负载均衡

    signalR是相当不错的websocket应用,最近要做集群和负载均衡 主要用到了redis进行集群,signalR的backplane集成redis. 细节,订阅redis之后注意database ...

  3. python自动拉取备份压缩包并删除3天前的旧备份

    业务场景,异地机房自动拉取已备份好的tar.gz数据库压缩包,并且只保留3天内的压缩包文件,用python实现 #!/usr/bin/env python import requests,time,o ...

  4. java正则匹配并提取字串

    Pattern p = Pattern.compile("\\(.*\\)"); Matcher m = p.matcher("1.2.0(23)"); if( ...

  5. 【Unity3D与23种设计模式】工厂方法模式(Factory Method)

    GoF中定义: "定义一个可以产生对象的接口,但是让子类决定要产生哪一个类的对象.工厂方法模式让类的实例化程序延迟到子类中实施" 当类的对象产生时,若出现下列情况: 1.需要复杂的 ...

  6. Maven打包的三种方式(转)

    Maven可以使用mvn package指令对项目进行打包,如果使用Java -jar xxx.jar执行运行jar文件,会出现"no main manifest attribute, in ...

  7. 【前端】input radio多选事件获取所有选中的id,radio样式优化可修改

    $("#all_button").on('click', function() { obj = document.getElementsByClassName("inpu ...

  8. thinkphp5多图上传 js部分

    在项目中常会用到多图上上传,那就需要多图上传后需要预览,并且能删掉传错(不想传)的图,然而 测试了半天 并不知道jq怎么写,parent()parents()用了半天无果,罢了,还是用原生js来写.这 ...

  9. Docker + webpack 打包前端项目

    码云代码地址: https://gitee.com/caonimashi/docker_deployment_front_end    构建基础镜像: 1.下载一个 Apline Linux 操作系统 ...

  10. redis备份与恢复

    1.redis的备份 redis需要远程访问 添加密码进行登录,修改主配置文件添加:requirepass xxx redis-cli -h 127.0.0.1 -p 6379 -a 123456 b ...