question

JerryLipan-2008 avatar image
0 Votes"
JerryLipan-2008 asked LeonLu-MSFT commented

Need help in Login Page. How to handle 400 Bad Request

I'm a Xamarin Newbie. Just tried to develop Login Page. Everything is fine. Only if, don't know how to handle - 400 Bad Request

109452-login-invalid-return-bad-request.png

Web API ( Models )

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Threading.Tasks;
    
 namespace App1Service.Models
 {
    
     public class User
     {
         public string userId { get; set; }
     }
    
     public class LoginApiResponseModels
     {
         public string authenticationToken { get; set; }
         public User user { get; set; }
    
     }
 }

Web API ( Controller )

 using Microsoft.AspNetCore.Http;
 using Microsoft.AspNetCore.Mvc;
 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Threading.Tasks;
 using App1Service.Models;
 using Microsoft.EntityFrameworkCore;
 using Microsoft.Extensions.Configuration;
 using Microsoft.IdentityModel.Tokens;
 using System.IdentityModel.Tokens.Jwt;
 using System.Security.Claims;
 using System.Text;
    
    
 namespace App1Service.Controllers
 {
     [Route("api/[controller]")]
     [ApiController]
     public class TokenController : ControllerBase
     {
         public IConfiguration _configuration;
         private readonly MusalmahDbContext _context;
    
         public TokenController(IConfiguration config, MusalmahDbContext context)
         {
             _configuration = config;
             _context = context;
         }
    
         [HttpPost]
         public async Task<IActionResult> Post(UserInfo _userData)
         {
    
             if (_userData != null && _userData.Email != null && _userData.Password != null)
             {
                 var user = await GetUser(_userData.Email, _userData.Password);
    
                 if (user != null)
                 {
                     //create claims details based on the user information
                     var claims = new[] {
                     new Claim(JwtRegisteredClaimNames.Sub, _configuration["Jwt:Subject"]),
                     new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                     new Claim(JwtRegisteredClaimNames.Iat, DateTime.UtcNow.ToString()),
                     new Claim("Id", user.UserId.ToString()),
                     new Claim("FirstName", user.FirstName),
                     new Claim("LastName", user.LastName),
                     new Claim("UserName", user.UserName),
                     new Claim("Email", user.Email)
                    };
    
                     var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:Key"]));
    
                     var signIn = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
    
                     var token = new JwtSecurityToken(_configuration["Jwt:Issuer"], _configuration["Jwt:Audience"], claims, expires: DateTime.UtcNow.AddDays(1), signingCredentials: signIn);
                        
                     LoginApiResponseModels model = new LoginApiResponseModels();
                     model.authenticationToken = new JwtSecurityTokenHandler().WriteToken(token);
                     model.user = new User();
                     model.user.userId = user.UserId.ToString();
                     return Ok(model);
    
                 }
                 else
                 {
                     return BadRequest("Invalid credentials");
                        
                 }
             }
             else
             {
                 return BadRequest();
             }
         }
    
         private async Task<UserInfo> GetUser(string email, string password)
         {
             return await _context.UserInfo.FirstOrDefaultAsync(u => u.Email == email && u.Password == password);
         }
    
    
     }
    
    
    
 }

My code CAN HANDLE this Json return

109453-login-valid-return-response.png

 public async Task<LoginApiResponseModel> AuthenticateUserAsync(string phonenumber, string password)
         {
             try
             {
                 LoginApiRequestModel loginRequestModel = new LoginApiRequestModel()
                 {
                     Email = phonenumber,
                     Password = password
    
                 };
                 var content = new StringContent(JsonConvert.SerializeObject(loginRequestModel), Encoding.UTF8, "application/json");
                 //Change your base address tail part here and post it. 
                 //var response = await client.PostAsync("xxxxxx/xxxx/xxx", content);
                 var response = await client.PostAsync("api/token", content);
                 response.EnsureSuccessStatusCode();
                 using (var stream = await response.Content.ReadAsStreamAsync())
                 using (var reader = new StreamReader(stream))
                 using (var json = new JsonTextReader(reader))
                 {
                     var jsoncontent = _serializer.Deserialize<LoginApiResponseModel>(json);
                     Preferences.Set("authToken", jsoncontent.authenticationToken);
                     return jsoncontent;
                 }
             }
             catch (Exception ex)
             {
                 return null;
             }
         }


BUT CANNOT handle this,
109405-login-valid-bad-request.png

 public async Task<LoginApiResponseModel> AuthenticateUserAsync(string phonenumber, string password)
         {
             try
             {
                 LoginApiRequestModel loginRequestModel = new LoginApiRequestModel()
                 {
                     Email = phonenumber,
                     Password = password
    
                 };
                 var content = new StringContent(JsonConvert.SerializeObject(loginRequestModel), Encoding.UTF8, "application/json");
                 //Change your base address tail part here and post it. 
                 //var response = await client.PostAsync("xxxxxx/xxxx/xxx", content);
                 var response = await client.PostAsync("api/token", content);
                 response.EnsureSuccessStatusCode();
                 using (var stream = await response.Content.ReadAsStreamAsync())
                 using (var reader = new StreamReader(stream))
                 using (var json = new JsonTextReader(reader))
                 {
                     var jsoncontent = _serializer.Deserialize<LoginApiResponseModel>(json);
                     Preferences.Set("authToken", jsoncontent.authenticationToken);
                     return jsoncontent;
                 }
             }
             catch (Exception ex)
             {
                 return null;
             }
         }

This is the debugging,

109413-login-invalid-into-exception.png

109427-login-invalid-no-token.png


How to make it my Xamarin runtime is error free ? Please help


dotnet-xamarin
· 3
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

the 400 Bad Request E rror is an Http response status code that indicates that the server was unable to process the request send by client due to invalid syntax. I find a similar thread, you can refer to it.https://forums.xamarin.com/discussion/170701/status-code-400-bad-request-and-json-the-request-is-invalid

1 Vote 1 ·

Awesome. Thanks

0 Votes 0 ·

You are welcome.

0 Votes 0 ·

0 Answers