我是新来的Asp.Net,我想要做的是。我有一个用于登录服务的Web API,它返回一个json数据。网页APIAsp.net MVC调用登录Web服务
http://localhost:55500/api/Login/submit?username=abc&password=abc123
的示例URL,它返回一个JSON数据,如
[{"UserID":0,
"Status":"True",
"Name":"885032-59-6715",
"DepName":"Ajay"}
]
我怎样才能在Asp.NET MVC验证自己的登录页面。如果登录成功(Status:True)。我应该重定向到仪表板并在我的视图页面中显示json数据。 如果登录不是全成,它应该显示错误消息
我的ASP.NET MVC模型CALSS文件:
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; }
}}
我的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();
}
当我试图用这个上面的代码登录。它总是显示“无效的用户名或密码”。所以在此先感谢您的帮助。展望未来成功
由于dime2lo下面贴你需要使用'json.net'(或其他库)反序列化'responseData'一个对象,然后检查'status'财产。你也应该对你的查询字符串参数进行URL编码。 – Igor