我是新來的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