c# - Making a generic-body method -


i'm writing web api. quite tired of checking if model valid , embracing method try , catch clauses. reason wrote method try that. works asynchronously.

here code below works:

[route("account/[controller]")] public class logincontroller : controller {     private static async task<status> try(modelstatedictionary modelstate, func<task<status>> func)     {         try         {             return modelstate.isvalid ? await func() : status.invalidformat;         }         catch         {             return status.invalidformat;         }     }      [httppost]     public async task<status> login(accountloginmodel model)         => await try(modelstate, async () =>     {         // yaaay! i'm safe! model valid!         // , if bad happens, exception caught!!         // let's something...          return await task.fromresult(status.ok);     }); } 

my question is: possible make shorter, simpler, clearer? still don't ugly large line:

public async task<status> login(accountloginmodel model)     => await try(modelstate, async () => 

what can make code better? or there structure possible implement make job done?

edit

my version:

using microsoft.aspnet.mvc;  public class validateattribute : actionfilterattribute {     public override void onactionexecuting(actionexecutingcontext context)     {         if (context.modelstate.isvalid == false)         {             context.httpcontext.response.statuscode = 400;             context.result = new jsonresult(/* stuff */);         }     } } 

you can use validation filter , register filter check model validation time this:

public class validationfilter : actionfilterattribute {     /// <summary>     /// occurs before action method invoked.     /// </summary>     /// <param name="actioncontext">the action context.</param>     public override void onactionexecuting(httpactioncontext actioncontext)     {         if (!actioncontext.modelstate.isvalid)         {             actioncontext.response = actioncontext                 .request                 .createerrorresponse(httpstatuscode.badrequest, actioncontext.modelstate);         }     } } 

and in webapiconfig register method should register validation filter this:

config.filters.add(validationfilter); 

Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -