Sunday, 15 September 2013

c# - How can I consolidate all of my "setup code" away from my WebAPI controllers? -



c# - How can I consolidate all of my "setup code" away from my WebAPI controllers? -

all of controllers this:

[httpput] [route("api/businessname")] [authorize] public httpresponsemessage updatebusinessname(businessnamedto model) { if (!modelstate.isvalid) homecoming request.createerrorresponse(httpstatuscode.badrequest, modelstate); seek { _userservice.updatebusinessname(user.identity.name, model.businessname); homecoming request.createresponse(httpstatuscode.ok, new apiresponsedto() {}); } grab (exception e) { // logging code //return request.createresponse(httpstatuscode.internalservererror, e); homecoming request.createresponse(httpstatuscode.ok, new apiresponsedto() { success = false, error = "something bad happened :(" }); } }

there's lot of repeated stuff across controllers. ideally have this:

[httpput] [route("api/businessname")] [authorize] public httpresponsemessage updatebusinessname(businessnamedto model) { _userservice.updatebusinessname(user.identity.name, model.businessname); homecoming request.createresponse(httpstatuscode.ok, new apiresponsedto() {}); }

and tell webapi other stuff every controller... don't know if that's possible. how can create happen?

you ca following:

1) create validation filter action method executes if model state valid. don't need check modelstate.isvalid anymore in action methods.

public class validationactionfilter : actionfilterattribute { public override void onactionexecuting(httpactioncontext actioncontext) { modelstatedictionary modelstate = actioncontext.modelstate; if (!modelstate.isvalid) { actioncontext.response = actioncontext.request.createerrorresponse( httpstatuscode.badrequest, modelstate); } } }

2) create exception handling filter grab exception thrown action method, serialize , create http badrequest response message client. don't have utilize seek grab anymore in action methods.

public class handleexceptionfilter : exceptionfilterattribute { public override void onexception(httpactionexecutedcontext context) { var responsemessage = new httpresponsemessage(httpstatuscode.badrequest); responsemessage.content = new stringcontent(context.exception.message); context.response = responsemessage; } }

you can register these filters in webapiconfig.cs adding below lines it

config.filters.add(new validationactionfilter()); config.filters.add(new handleexceptionfilter());

update: more specific sb2055's scenario, adding below code

public class handleexceptionfilter : exceptionfilterattribute { public override void onexception(httpactionexecutedcontext context) { var model = new apiresponsedto() { success = false, error = context.exception.message }) context.response = context.request.createresponse(httpstatuscode.ok, model); } }

c# asp.net-mvc asp.net-web-api

No comments:

Post a Comment