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
responseDatato an object usingjson.net(or some other library) and then check thestatusproperty. Also you should URL encode your query string parameters.