c# - Register new user in Web API -


i new web api. trying implement token authentication in api. have created web api 2 project , console app testing service.

  1. register new time users
  2. authenticate registered users , generate token
  3. client uses generated token subsequent requests until token expiry

below code hits api.

class program {     static void main(string[] args)     {         try         {             task t = new program().register("user@domain.com", "abc123!", "abc123!");             console.readkey();         }         catch (exception ex)         {          }     }      public async task register(string username, string password, string confirmpassword)     {         registermodel model = new registermodel         {             confirmpassword = confirmpassword,             password = password,             username = username         };          httpwebrequest request = (httpwebrequest)webrequest.create("http://localhost:61086/api/account/register");         request.method = "post";         request.contenttype = "application/json";         request.accept = "application/json";         string json = jsonconvert.serializeobject(model);         byte[] bytes = encoding.utf8.getbytes(json);         using (stream stream = await request.getrequeststreamasync())         {             stream.write(bytes, 0, bytes.length);         }          try         {             await request.getresponseasync();             //return true;         }         catch (exception ex)         {             //return false;         }         //return request.getresponseasync() task<webresponse>;     } }  class registermodel {     public string username { get; set; }     public string password { get; set; }     public string confirmpassword { get; set; } } 

i result 'waitingforactivation'. can tell me if doing wrong or suggest better approach? please let me know if improve answer.

you're getting "waitingforactivation" result because creating asynchronous http request making synchronously without waiting request complete.

when call register() method getting task represents continuation of register() method rather method itself.

the "waitingforactivation" status on task means work within register() has yet finish returned task hasn't been activated yet.

if wait task t complete should have expected response rather "waitingforactivation".

task t = new program().register("user@domain.com", "abc123!", "abc123!"); t.wait(); // wait task complete console.readkey(); 

take @ async/await documentation further explanation.


Comments