动态类型实现HATEOAS
1.对于单个资源可以用ExpandoObject
2.对于集合资源使用匿名类.
实现:
1.新建一个类:LinkResource.cs,实现3个属性
public class LinkResource { public LinkResource(string href, string rel, string method) { Href = href; Rel = rel; Method = method; } public string Href { get; set; } public string Rel { get; set; } public string Method { get; set; } }
2.在PostController.cs添加方法
private IEnumerable<LinkResource> CreateLinksForPost(int id, string fields = null) { var links = new List<LinkResource>(); if (string.IsNullOrWhiteSpace(fields)) { links.Add( new LinkResource( _urlHelper.Link("GetPost", new { id }), "self", "GET")); } else { links.Add( new LinkResource( _urlHelper.Link("GetPost", new { id, fields }), "self", "GET")); } links.Add( new LinkResource( _urlHelper.Link("DeletePost", new { id }), "delete_post", "DELETE")); return links; } private IEnumerable<LinkResource> CreateLinksForPosts(PostParameters postResourceParameters, bool hasPrevious, bool hasNext) { var links = new List<LinkResource> { new LinkResource( CreatePostUri(postResourceParameters, PaginationResourceUriType.CurrentPage), "self", "GET") }; if (hasPrevious) { links.Add( new LinkResource( CreatePostUri(postResourceParameters, PaginationResourceUriType.PreviousPage), "previous_page", "GET")); } if (hasNext) { links.Add( new LinkResource( CreatePostUri(postResourceParameters, PaginationResourceUriType.NextPage), "next_page", "GET")); } return links; }
[HttpGet("{id}")] 修改为 [HttpGet("{id}",Name="GetPost")]