Making a Rest Api Call

I want to call a RestApi I developed to check if there is an user with the inputed credentials.
How can I make the call? If I want to follow a object oriented approach should I create a class with the Api Calls?

public virtual void Login(object _info)
        {
            string tempUsername = loginMenu.GetUsernameInput().GetInputText();
            string tempPassword = loginMenu.GetPasswordInput().GetInputText();
            if (tempUsername.Equals("") || tempPassword.Equals(""))
            {
                // no login with missing credentials
                loginMenu.SetWrongInfo(false);
                loginMenu.SetEmptyInfo(true);
            }

            else
            {
                //Call API
                if(tempUsername.Equals("bla") && tempPassword.Equals("bla")){           //replace values with values from Api

                    gameplay.GetUser().SetUsername(tempUsername);
                    ChangeUserChoice(1);
                }
                else
                {
                    loginMenu.SetEmptyInfo(false);
                    loginMenu.SetWrongInfo(true);
                }

               
            }
        }

Here is a sample on creating a RESTful API call to a login action. Because you are making a call over the internet you need to do is asynchronously. It requires the three fields/constants in order to work. Basically you create an HttpClient, point it at your web service, set the parameters ,make the call then analyze the response.

        private readonly HttpClient _client = new HttpClient();
        const string Uri = "http://10.0.2.2/";
        const int Port = 80;

        public async Task<string> Login(string username, string password)
        {
            string response;

            try
            {
                var builder = new UriBuilder(Uri + "/Api/Account/Login/")
                {
                    Port = Port
                };
                builder.Query = $"UserName={username}&Password={password}";
                response = await _client.GetStringAsync(builder.Uri.AbsoluteUri);
                if (response == "\"failure\"")
                {
                    response = null;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("\tERROR {0}", ex.Message);
                response = null;
            }

            return response;
        }
    }

But do I create a class for this or should I do it in Program?

It is just a method inside your existing class.

If it was me, I would create a separate class for communication with the server. This way if you need to change how you communicate, you can change it in one place. You could also substitute it out if you wanted to support multiple types of communication (such as REST, WCF, WebService, etc…).

1 Like

In my my backend my login method returns a User so instead of Async should I use Async?

 [HttpPost("Login")]
        public IActionResult Authenticate([FromBody]AuthenticateModel userModel)
        {
            
            var user = _userService.Authenticate(userModel.Username, userModel.Password);

            if(user == null)
            {
                return BadRequest(new { message = "Username or Password invalid" });
            }

            var tokenHandler = new JwtSecurityTokenHandler();
            
            var key = Encoding.ASCII.GetBytes(_appSettings.Secret);

            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.Id.ToString())
                }),
                Expires = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };

            var token = tokenHandler.CreateToken(tokenDescriptor);

            var tokenString = tokenHandler.WriteToken(token);

            return Ok(new
            {
                Id = user.Id,
                UserName = user.Username,
                Token = tokenString
            }) ;
        }

It is returning JSON. You just need to parse it using something like Newtonsoft.

in the videogame?

Only noticed now that some parts of my question were deleted

"Should I replace

Async<string>

by

Async<User>

String is fine as that is what is returned by the call. It is JSON. You just need tto parse the JSON in your game to get the user. I’m on my phone so I can’t give you an example.

I have done this . Any advantage on parsing the response when I call Login instead of just doing it inside the method?

public async Task<User> Login(string username, string password)
        {
            string response;
            User user = null;

            try
            {
                var builder = new UriBuilder(Uri + "/Api/Account/Login/")
                {
                    Port = Port
                };
                builder.Query = $"Username={username}&Password={password}";
                response = await _client.GetStringAsync(builder.Uri.AbsoluteUri);
               
                if (response == "OK")
                {
                    
                    user = JsonConvert.DeserializeObject<User>(response);

                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("\tERROR {0}", ex.Message);
                
            }

            return user;
        }

Also my model in my game doesn´t have Token. Will there be a problem?

public class User
    {
        private int Id;
        private string Username;

        public User(int _id,string _username)
        {
            Id = _id;
            Username = _username;

        }

        public User()
        {

        }

        public int GetId()
        {
            return Id;
        }

        public void SetId(int _id)
        {
            Id = _id;
        }

        public string GetUsername()
        {
            return Username;
        }

        public void SetUsername(string _username)
        {
            Username = _username;
        }
    }

You will need a Token.

I am geting this error. Am I calling the method wrong? Or should I make my method async?

Looks like you might need a cast…

Already solved that but my api call always goes to exception .Translating it means " [No connection could be made because the target machine actively refused it"

Then addressing or your credentials could be wrong i guess…

Should I be using GetStringAsync since my login is a POST?

That looks more to be an error in coms, go you need to set any credentials in the header?

Sorry, I didn´t understand