I know this is an old thread but you might want to take a look at my solution here. Its a little more than needed but sure will do the job.
Steps:
Define a custom attribute:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public sealed class UniqueIdAttribute: Attribute
{
}
Decorate the uniquely identifying property of your model with a custom attribute:
public class Model
{
public List<Model> ChildModels { get; set; }
[UniqueId]
public Guid ModelId { set; get; }
public Guid ? ParentId { set; get; }
public List<SomeOtherObject> OtherObjects { set; get; }
}
Add a new Created(T yourobject);
method to a BaseController which inherits from ApiController. Inherit all your controllers from this BaseController:
CreatedNegotiatedContentResult<T> Created<T>(T content)
{
var props =typeof(T).GetProperties()
.Where(prop => Attribute.IsDefined(prop, typeof(UniqueIdAttribute)));
if (props.Count() == 0)
{
//log this, the UniqueId attribute is not defined for this model
return base.Created(Request.RequestUri.ToString(), content);
}
var id = props.FirstOrDefault().GetValue(content).ToString();
return base.Created(new Uri(Request.RequestUri + id), content);
}
Its pretty simple without having to worry about writing so much in every method. All you got to do is just call Created(yourobject);
The Created() method would still work if you forget to decorate or cannot decorate your model(for some reason). The location header would miss the Id though.
Your unit test for that controller should take care of this.