asp.net - Return HttpStatusCode in API method -
how return httpstatus code api methods in asp.net core 1.0 if there's problem?
if method supposed return particular object type, when try return http status code, error saying can't convert object status code.
[httppost] public async task<someobject> post([frombody] inputdata) { // detect error , want return badrequest httpstatus if(inputdata == null) return new httpstatuscode(400); // well, return object return myobject; }
return iactionresult
controller action instead:
public async task<iactionresult> post([frombody] inputdata inputdata) { if(inputdata == null) { return new httpstatuscoderesult((int) httpstatuscode.badrequest); } //... return ok(myobject); }
if instead want remove such null checks controller define custom attribute:
public class checkmodelfornullattribute : actionfilterattribute { public override void onactionexecuting(actionexecutingcontext context) { if (context.actionarguments.any(k => k.value == null)) { context.result = new badrequestobjectresult("the model cannot null"); } } }
this way dont have bother model being null in action.
[httppost] [checkmodelfornull] public async task<someobject> post([frombody]inputdata inputdata) { // attribute protects me null // ... return myobject; }
Comments
Post a Comment