c# - Specify a unique identifier attribute for an object across webapi Models -
in post call webapi trying return created(newobject) thing. there no signature created in apicontroller can take object , rest.
it works fine if return like:
return created(newobject.blahid.tostring(), newobject);
or if
return createdatroute("defaultapi", new { controller = controllercontext.controllerdescriptor.controllername, id = newobject.blahid.tostring()}, newobject);
i want simplify to:
return created(newobject);
i need implement method in basecontroller
public class basecontroller : apicontroller { protected new creatednegotiatedcontentresult<t> created<t>(t content) { var id = getid(content);//need here return base.created(id, content); } }
i don't want worry unique identifier object being called differently in different models e.g. myobjguid, someblahguid etc. want find out , mark "id".
say if model
public class model_a { public list<model_a> childmodels { get; set; } [lookforthisattribute]//i want public guid model_aguid { set; get; } public guid ? parentguid { set; get; } public list<someotherobject> otherobjects { set; get; } }
is there attribute([lookforthisattribute]) or can set on models specify guy assumed unique identifier if ever it.
just [key] attribute in entity framework. no matter call it, entity framework know going primary key.
so getid(t content) method can take object , return value of property has [lookforthisattribute]
set?
i ended writing own attribute , looking in basecontroller.
[attributeusage(attributetargets.property, allowmultiple = false)] public sealed class uniqueidattribute: attribute { }
and in basecontroller created method:
protected creatednegotiatedcontentresult<t> created<t>(t content) { var props =typeof(t).getproperties().where( prop => attribute.isdefined(prop, typeof(uniqueidattribute))); if (props.count() == 0) { //log return base.created(request.requesturi.tostring(), content); } var id = props.firstordefault().getvalue(content).tostring(); return base.created(new uri(request.requesturi + id), content); }
mark gravell's post here helped me getting value of property has custom attribute: how list of properties given attribute?
along corresponding unit test controllers works fine me.
now can call created(anyobject);
apicontrollers without bothering different names people put ids long decorate custom attribute.