c# - call another api controller -


when call user controller (api/user), able pass user credentials, application crashes null exception error (value cannot null) in values controller:

   public class valuescontroller : apicontroller    {    private cdwentities db = new cdwentities();     public httpresponsemessage get([fromuri] query query)    {        var data = db.database.asqueryable();         if (query.name != null)        {            data = data.where(c => c.name == query.name);        }         if (query.price != null)        {            data = data.where(c => c.price == query.price);        }          if (!data.any())        {            var message = string.format("error");            return request.createerrorresponse(httpstatuscode.notfound, message);        }         ***return request.createresponse(httpstatuscode.ok, data);***    }  } 

i believe error because valuescontroller method cannot pass null values pass parameters(i.e. api/values/name=tom), hence when call user controller, throws null error because system has not passed parameters valuescontroller user controller.

public class usercontroller : apicontroller {     [authorize]     public httpresponsemessage get([fromuri] query query)     {         if (user.isinrole("user"))         {             var result = new itemcontroller();             return result.get(query);         }          var message = string.format("no data found");         return request.createerrorresponse(httpstatuscode.notfound, message);     } 

}

is built-in function use solve issue or framework/library should into? many , time.

you should not call 1 api endpoint method other api endpoint. instead need have proper segregation of code between api, business logic layer , data access layer. in following way -

api -

    public class usercontroller : apicontroller     {         [authorize]         public httpresponsemessage get([fromuri] query query)         {             businesslayer layer = new businesslayer();             if (user.isinrole("user"))             {                 var result = layer.getdata(query);                 // use result here , return httpresponsemessage                 var message = string.format("no data found");                 return request.createerrorresponse(httpstatuscode.notfound, message);             }         }     } 

and in business logic layer -

   public resultmodel get(query query)    {        // process model query here... , return meaningful result here...        // call data access layer methods here, instead of making direct database        // (entity framework) calls...    } 

for better flexible , loosely coupled systems, need have dependency injection (probably using unity, there many other options autofac, ninject etc.)


Comments

Popular posts from this blog

php - regexp cyrillic filename not matches -

c# - OpenXML hanging while writing elements -

sql - Select Query has unexpected multiple records (MS Access) -