Created
August 29, 2012 17:04
-
-
Save benfoster/3515675 to your computer and use it in GitHub Desktop.
Adding resource links in ASP.NET Web Api payloads
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ResourceLinksActionFilterAttribute : ActionFilterAttribute | |
{ | |
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext) | |
{ | |
ResourceModel payload; | |
if (actionExecutedContext.Response.TryGetContentValue<ResourceModel>(out payload)) | |
{ | |
payload.BuildResourceLinks(actionExecutedContext.Request); | |
} | |
base.OnActionExecuted(actionExecutedContext); | |
} | |
} | |
public class ResourceModel | |
{ | |
public ICollection<Link> Links { get; set; } | |
public ResourceModel() | |
{ | |
Links = new List<Link>(); | |
} | |
public virtual void BuildResourceLinks(HttpRequestMessage request) | |
{ | |
AddSelfLink(request); | |
} | |
protected void AddSelfLink(HttpRequestMessage request) | |
{ | |
Links.Add(new Link { Rel = "Self", Href = request.RequestUri.AbsoluteUri }); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment