简体   繁体   English

Asp.net MVC调用登录Web服务

[英]Asp.net MVC calling Login web service

I am new to Asp.Net, What i want to do is . 我是Asp.Net的新手,我想做的是。 I have a Web API for Login service , that returns a json Data. 我有一个用于登录服务的Web API,它返回一个json数据。 Sample url of Web APi Web APi的示例URL

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

It returns a json data like 它返回一个json数据,例如

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

How can i authenticate my login page in Asp.NET MVC. 如何在Asp.NET MVC中验证我的登录页面。 If login success (Status:True). 如果登录成功(状态:真)。 I should redirect to dashboard and display the json data in my view page. 我应该重定向到仪表板,并在我的视图页面中显示json数据。 If login not successfull, it should show the error message 如果登录失败,则应显示错误消息

My ASP.NET MVC model calss File : 我的ASP.NET MVC模型校准文件:

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 : 我的ASP.NET MVC控制器文件:

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. 当您使用ReadAsStringAsync() ,响应可能返回您提到的JSON [{"UserID":0,"Status":"True","Name":"885032-59-6715","DepName":"Ajay"}]什么意味着测试responseData=="true"又名。 "[{"UserID":0,"Status":"True","Name":"885032-59-6715","DepName":"Ajay"}]" == "true" will result in being false. "[{"UserID":0,"Status":"True","Name":"885032-59-6715","DepName":"Ajay"}]" == "true"将导致错误。

You could use responseData.Contains("true") but I don´t believe this is the best approach. 您可以使用responseData.Contains("true")但我不认为这是最好的方法。

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); 我认为方法是,在ReadAsStringAsync() ,应通过JsonConvert.DeserializeObject<LoginResultModel>(responseData);将字符串(json)反序列化为对象JsonConvert.DeserializeObject<LoginResultModel>(responseData); . The JsonConvert is in Newtonsoft.Json that you can get by Nuget. JsonConvert在Newtonsoft中。您可以通过Nuget获得Json。 In the LoginResultModel you should create considering your json. 在LoginResultModel中,应考虑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); 在返回数组时,应反序列化到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. PS .:您可以进行调试以查看responseData所获取的数据,并了解其评估为false的原因。

Regards 问候

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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