I am getting different response on hitting the same API. Sometimes its 200, and sometimes its showing cancelled. When I am hitting the API from Postman, its working absolutely fine but when I am hitting API from the js file, its showing this error in the network tab. Tried using Fetch but still facing the same issue.
Here is my API code
using PostQuestion.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
namespace PostQuestion.Controllers
{
public class LoginController : ApiController
{
public string conString = "Data Source=DESKTOP-DO57SLF\\SQLEXPRESS;Initial Catalog=doubtdb;Integrated Security=True";
[HttpPost]
[Route("login")]
[ResponseType(typeof(LoginResponse))]
public IHttpActionResult Login([FromBody] LoginRequest login)
{
LoginResponse res = new LoginResponse();
if (string.IsNullOrEmpty(login.Username))
{
res.Success = false;
res.Message = "Username can not be empty";
return Ok(res);
}
if (string.IsNullOrEmpty(login.Password))
{
res.Success = false;
res.Message = "Password can not be empty";
return Ok(res);
}
try
{
SqlConnection con = new SqlConnection(conString);
con.Open();
if (con.State == System.Data.ConnectionState.Open)
{
String Username = login.Username.Trim();
String Password = login.Password.Trim();
if (Username.Contains(" "))
{
res.Success = false;
res.Message = "Invalid Credentials!";
return Ok(res);
}
if (Username.Contains('=') && Username.Contains("or"))
{
res.Success = false;
res.Message = "Invalid Credentials!";
return Ok(res);
}
SqlCommand cmd = new SqlCommand("spchecklogin", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.Add("@Username", SqlDbType.VarChar).Value = Username;
cmd.Parameters.Add("@Password", SqlDbType.VarChar).Value = Password;
cmd.Parameters.Add("@Count", SqlDbType.Int).Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
int getcount = Convert.ToInt32(cmd.Parameters["@Count"].Value);
con.Close();
if (getcount == 1)
{
res.Success = true;
res.Message = "Login Successful!";
return Ok(res);
}
else
{
res.Success = false;
res.Message = "Invalid Credentials!";
return Ok(res);
}
}
else
{
res.Success = false;
res.Message = "Unable to Login";
return Ok(res);
}
}
catch (Exception ex)
{
res.Success = false;
res.Message = "Unable to Login" + ex;
return Ok(res);
}
}
}
}
Here is my js code:
function Login() {
var username=document.getElementById("Email").value;
var password=document.getElementById("Password").value;
var xhttp = new XMLHttpRequest();
var raw = JSON.stringify({"Username":username,"Password":password});
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
xhttp.open("POST", "https://localhost:44393/login", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send(raw);
}