简体   繁体   中英

Asp.net MVC calling Login web service

I am new to Asp.Net, What i want to do is . I have a Web API for Login service , that returns a json Data. Sample url of Web APi

http://localhost:55500/api/Login/submit?username=abc&password=abc123

It returns a json data like

[{"UserID":0,
  "Status":"True",
  "Name":"885032-59-6715",
  "DepName":"Ajay"} 
]

How can i authenticate my login page in Asp.NET MVC. If login success (Status:True). I should redirect to dashboard and display the json data in my view page. If login not successfull, it should show the error message

My ASP.NET MVC model calss File :

namespace LoginPracticeApplication.Models{
  public class Login {

    [Required(ErrorMessage = "Username is required")] // make the field required
    [Display(Name = "username")]  // Set the display name of the field
    public string username { get; set; }

    [Required(ErrorMessage = "Password is required")]
    [Display(Name = "password")]
    public string password { get; set; }       
  }}

My ASP.NET MVC Controller File :

public ActionResult Index(Login login)
{
  if (ModelState.IsValid) // Check the model state for any validation errors
  {
      string uname = "";
      uname = login.username;
      string pword = "";
      pword = login.password;

      string url = "http://localhost:55506/api/Login/submit?username=" + uname + "&password=" + login.password + "";
      System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
      client.BaseAddress = new Uri(url);
      client.DefaultRequestHeaders.Accept.Clear();
      client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
      HttpResponseMessage responseMessage = client.GetAsync(url).Result;

      var responseData = responseMessage.Content.ReadAsStringAsync().Result;
      if (responseData=="true")
      {                    
          return View("Show", login); // Return the "Show.cshtml" view if user is valid
      }
      else
      {
          ViewBag.Message = "Invalid Username or Password";
          return View(); //return the same view with message "Invalid Username or Password"
      }
  }
  else
  {
      return View();
  }
  return View();
}

When i tried to login with this above code. It always shows "Invalid Username or Password". So thanks in advance for your help. Looking forward for success

I believe that the problem is at:

          var responseData = responseMessage.Content.ReadAsStringAsync().Result;
          if (responseData=="true")
          {                    
              return View("Show", login); // Return the "Show.cshtml" view if user is valid
          }
          else
          {
              ViewBag.Message = "Invalid Username or Password";
              return View(); //return the same view with message "Invalid Username or Password"
          }

As you are ReadAsStringAsync() the response, probably is returning the JSON that you mentioned [{"UserID":0,"Status":"True","Name":"885032-59-6715","DepName":"Ajay"}] what means that the test responseData=="true" aka. "[{"UserID":0,"Status":"True","Name":"885032-59-6715","DepName":"Ajay"}]" == "true" will result in being false.

You could use responseData.Contains("true") but I don´t believe this is the best approach.

I think that the way to go is, after you ReadAsStringAsync() you should deserialize the string (json) into an object through JsonConvert.DeserializeObject<LoginResultModel>(responseData); . The JsonConvert is in Newtonsoft.Json that you can get by Nuget. In the LoginResultModel you should create considering your json. I believe it would be something like:

public class LoginResultModel
{
    public int UserID { get; set; }

    public bool Status { get; set; }

    public string Name { get; set; }

    public string DepName { get; set; }
}

And as you are returning an array you should deserialize to a list of LoginResultModel: JsonConvert.DeserializeObject<List<LoginResultModel>>(responseData);

PS.: You could have debug to see the data that responseData was getting and understand why it was evaluating to false.

Regards

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM