[英]Proper approach to create hypermedia in c# webapi
我正在研究如何為特定資源實現超媒體,但找不到真正的實現示例,只是抽象......
你知道,在各種文章中,這個人創建了一個方法:
public List<Link> CreateLinks(int id)
{
...//Here the guy put these three dots, whyyyyyyyyyy?
}
到目前為止我所擁有的:
public Appointment Post(Appointment appointment)
{
//for sake of simplicity, just returning same appointment
appointment = new Appointment{
Date = DateTime.Now,
Doctor = "Dr. Who",
Slot = 1234,
HyperMedia = new List<HyperMedia>
{
new HyperMedia{ Href = "/slot/1234", Rel = "delete" },
new HyperMedia{ Href = "/slot/1234", Rel = "put" },
}
};
return appointment;
}
和預約課程:
public class Appointment
{
[JsonProperty("doctor")]
public string Doctor { get; set; }
[JsonProperty("slot")]
public int Slot { get; set; }
[JsonProperty("date")]
public DateTime Date { get; set; }
[JsonProperty("links")]
public List<HyperMedia> HyperMedia { get; set; }
}
public class HyperMedia
{
[JsonProperty("rel")]
public string Rel { get; set; }
[JsonProperty("href")]
public string Href { get; set; }
}
有沒有正確的方法? 我的意思是,沒有硬編碼鏈接? 如何為給定類型動態創建它們,即約會類?
我正在使用c#Webapi,而不是c#MVC。
要將路由動態添加到HyperMedia集合,您可以使用路由命名:
使用特定名稱定義路由(例如,刪除):
[Route("{id:int}", Name = "AppointmentDeletion")] public IHttpActionResult Delete(int slot) { //your code }
通過UrlHelper.Link方法使用它:
public Appointment Post(Appointment appointment) { appointment = new Appointment { HyperMedia = new List<HyperMedia> { new HyperMedia { Href = Url.Link("AppointmentDeletion", new { slot = 1234 }), Rel = "delete" } } return appointment; };
也可以動態地將鏈接添加到結果對象,而無需為每個類聲明HyperMedia屬性:
定義沒有鏈接的類:
public class Appointment { [JsonProperty("doctor")] public string Doctor { get; set; } [JsonProperty("slot")] public int Slot { get; set; } [JsonProperty("date")] public DateTime Date { get; set; } }
定義擴展方法:
public static class LinkExtensions { public static dynamic AddLinks<T>(this T content, params object[] links) { IDictionary<string, object> result = new ExpandoObject(); typeof (T) .GetProperties(BindingFlags.Public | BindingFlags.Instance) .ToList() .ForEach(_ => result[_.Name.ToLower()] = _.GetValue(content)); result["links"] = links; return result; } }
用它:
public IHttpActionResult Post(Appointment appointment) { return Ok(appointment.AddLinks(new HyperMedia { Href = Url.Link("AppointmentDeletion", new { slot = 1234 }), Rel = "delete" })); }
你絕對可以將Rel
提取到Enum
(實際上是2,標准的 - Delete
, Put
等 - 以及自定義的 - 后者可以包含自定義關系,如customer-by-id
)。
你也可以動態地構建Href
參數(從對象的屬性中提取參數),但對於資源本身......你可能會堅持使用硬編碼(你也可以看一下反射)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.