400 Bad Request from a REST Service - ajax

I am trying to interact with a REST service by passing Json data to the operation contract URL using AJAX, but I keep getting a Bad Request and don't understand why.
I am cureently coding in Typescript, here is the method to do the Ajax Request:
AjaxLogin = (e: JQueryEventObject) : boolean =>
{
let email = $("#login-email").val();
let pwd = $("#login-pwd").val();
$.ajax({
cache: false,
type: "GET",
url: "http://localhost:57522/PizzaService.svc/Login",
data: '{"email":"' + email + '", "pwd":"' + pwd + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: this.LoginSuccess,
error: this.LoginError
});
e.preventDefault();
return false;
}
The operation contract in the REST service:
[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Bare,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "/Login")]
Entities.User LoginUser(string email, string pwd);
implemented C# method:
public User LoginUser(string email, string pwd)
{
SqlConnection db;
SqlCommand cmd;
SqlDataReader reader;
db = new SqlConnection(WebConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString);
cmd = new SqlCommand("SELECT * FROM Customer WHERE customerEmail = #email AND customerPassword = #pwd",db);
cmd.Parameters.AddWithValue("#email", email);
cmd.Parameters.AddWithValue("#pwd", pwd);
using (db)
{
db.Open();
reader = cmd.ExecuteReader();
if(reader.HasRows)
{
reader.Read();
int id = (int)reader["Id"];
string firstname = reader["customerFirstname"].ToString();
string lastname = reader["customerLastname"].ToString();
int houseno = (int)reader["customerHouseno"];
string postcode = reader["customerPostcode"].ToString();
string tel = reader["customerTel"].ToString();
return new User(id, firstname, lastname, houseno, postcode, tel, email, pwd);
}
else
{
return null;
}
}
}
Thanks, I really appreciate it.

Related

Getting Status 400 error while posting data on server in Razor page and AJAX

I am developing a website related to medical treatment, in which we ask different type of questions from patient actually, my task is, to enter their Email so I can check if he is already registered or not logged in then I redirect the user to the login page else I can register the user and assign a random password to the user and send him a mail on that Email,
so logged in user and if a user is not logged in these flows are working fine but when I'm when I register the user then and come to the next question I'm getting an error of status 400
Code for checking for user:
public async Task<IActionResult> OnGetCheckUserAsync(string Email)
{
if (User.Identity.IsAuthenticated)
{
var UserCred = _userManagmentServices.GetProfileAsync(Email).Result;
ProfileModel = new ProfileModel()
{
Id = UserCred.Id,
Email = UserCred.Email,
Name = UserCred.Name,
Applications = UserCred.Applications,
Address = UserCred.Address,
City = UserCred.City,
DisplayName = UserCred.DisplayName,
Phone = UserCred.Phone,
PostalCode = UserCred.PostalCode,
};
return new JsonResult(ProfileModel);
}
else
{
var user = await _userManager.FindByEmailAsync(Email);
if (user == null)
{
string randomString = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890!##$%^&*";
Random random = new Random();
char[] myPassword = new char[6];
for (int i = 0; i < 6; i++)
{
myPassword[i] = randomString[(int)(35 * random.NextDouble())];
}
var randomPassword = string.Concat(myPassword);
var UserModel = new UserModel()
{
Email = Email,
FirstName = "Mr",
LastName = "Patient",
Password = randomPassword,
PhoneNo = "03000000000",
};
var response = await _userManagmentServices.CreateAsync(UserModel);
if (response.IsSuccessful)
{
var Body = $"Dear {UserModel.FirstName + UserModel.LastName} Your password is auto generated successfull and your password is {UserModel.Password}";
await _mailServices.SendEmailNotificationAsync(UserModel.Email, "Auto Generated Password", Body);
}
if (!response.IsSuccessful)
{
foreach (var Error in response.Errors)
{
ModelState.AddModelError("", Error.ToString());
}
return new JsonResult("Error while creating your account");
}
var UserCred = _userManagmentServices.GetProfileAsync(UserModel.Email).Result;
ProfileModel = new ProfileModel()
{
Id = UserCred.Id,
Email = UserCred.Email,
Name = UserCred.Name,
Applications = UserCred.Applications,
Address = UserCred.Address,
City = UserCred.City,
DisplayName = UserCred.DisplayName,
Phone = UserCred.Phone,
PostalCode = UserCred.PostalCode,
};
return new JsonResult(ProfileModel);
}
else
{
application = new FEApplication();
application.Status = Status.Incomplete;
application.UserEmail = Email;
application.ApplicationType = "Premature Ejaculation";
application.FlowId = await _applicationManagementService.Create(application);
var _signinUrl = "../Auth/Signin";
return new JsonResult(_signinUrl);
}
}
}
public async Task<IActionResult> OnPostSubmitAsync(FEApplication? application)
{
if (application.FlowId != null)
{
application.ApplicationType = "Premature Ejaculation";
if (application.DoctorToKnow == "No" || application.ExplainDoctorToKnow != null)
{
application.Status = Status.PaymentDue;
}
else
{
application.Status = Status.Incomplete;
}
await _applicationManagementService.UpdatePEAsync(application.FlowId, application);
}
else
{
if (User.Identity.IsAuthenticated)
{
application.PatientUserName = ProfileModel.DisplayName;
application.ApplicationType = "Premature Ejaculation";
application.Status = Status.Incomplete;
application.UserEmail = User?.Identity?.Name;
ProfileModel = _userManagmentServices.GetProfileAsync(application.UserEmail).Result;
}
else
{
application.PatientUserName = ProfileModel.DisplayName ?? string.Empty;
application.UserEmail = application.UserEmail;
}
application.Status = Status.Incomplete;
application.ApplicationType = "Premature Ejaculation";
application.FlowId = await _applicationManagementService.Create(application);
//_application = _applicationManagementService.GetOneById(FlowId);
}
return new JsonResult(application.FlowId);
}
function CheckUserEmail() {
$("#modalspinner").show();
var email = document.getElementById("Email").value;
$.ajax({
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken" ]').val());
},
url: "./Start?handler=CheckUser",
type: "GET",
dataType: "json",
data: {
Email: email
},
success: function (response) {
console.log("Success block");
if (response) {
$("#modalspinner").hide();
console.log("response " + response)
if (response == "../Auth/Signin") {
window.location.href = response;
}
else {
if (response.id) {
console.log("if block =" + JSON.stringify(response));
var firstName = JSON.stringify(response.displayName) ?? "";
var lastName = JSON.stringify(response.displayName) ?? "";
var email = JSON.stringify(response.email) ?? "";
var phoneNo = JSON.stringify(response.phone);
var address = JSON.stringify(response.address) ?? "";
var city = JSON.stringify(response.city);
var postalCode = JSON.stringify(response.postalCode) ?? "";
$("#FirstName").val(firstName.replace(/\"/g, ""));
$("#LastName").val(lastName.replace(/\"/g, ""));
$("#Email").val(email.replace(/\"/g, ""));
$("#PhoneNoTextbox").val(phoneNo.replace(/\"/g, ""));
$("#CustomerShippingAddress").val(address.replace(/\"/g, ""));
$("#CustomerCity").val(city.replace(/\"/g, ""));
$("#CustomerPostalCode").val(postalCode.replace(/\"/g, ""));
console.log("response data :" + firstName, lastName, email, phoneNo, address, city, postalCode);
}
else {
$("#modalspinner").hide();
console.log("Error while creating new user" + JSON.stringify(response));
}
}
}
},
error: function (response) {
console.log("Error block =" + JSON.stringify(response));
$("#modalspinner").hide();
$('#EmailMessage').show();
setTimeout(function () { $('#EmailMessage').hide(); }, 5000);
$("#modalspinner").hide();
}
});
}
function SubmitForm() {
/*var flowId = document.getElementById("FlowId").value;*/
var data = $("#ApplicationData").serialize();
console.log("data :" + data);
$.ajax({
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken" ]').val());
},
type: "POST",
url: "./Start?handler=Submit",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: data,
success: function (response) {
var res = JSON.stringify(response);
console.log("Application data saved!");
$("#FlowId").val(res.replace(/\"/g, ""));
}
})
}
Please check below with your code:
In the cshtml, add
#Html.AntiForgeryToken()
The Ajax request should send the anti-forgery token in request header to the server.
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
In startup, since the script sends the token in a header called XSRF-TOKEN, configure the antiforgery service to look for the XSRF-TOKEN header:
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");

Get data from post request in WebApi

I want to get the data after post request call, I have the following code in client side:
function (data) {
console.log((data));
const requestOptions = {
headers: { 'Authorization': 'Bearer ' +
sessionStorage.getItem("accessToken") } };
return $http.post("/api/Account/Filter", data, requestOptions);
}
This is in server side:
public IHttpActionResult Filter(Models.DataSourceRequest request)
{
var employees = db.Users.OrderBy(ii => ii.Id).Select(x => new
RegisterBindingModel()
{
Id = x.Id,
Email = x.Email,
UserName = x.UserName,
FirstName = x.FirstName,
LastName = x.LastName,
Age = x.Age,
Phone = x.Phone,
Department = x.Department
});
var i = employees.ToDataSourceResult(request.Take, request.Skip, request.Sort, request.Filter);
var data = i.Data; // This is contain filtered data
request.Take = i.Total;
System.Diagnostics.Debug.WriteLine(Json(data));
return Json(i.Data);
}
How can I get the data to client side?

How to send several String to Spring?

How it's possible to send several string to spring? If I convert several Strings to the Array, I can send, but if I try to send several Strings it's not working. Send Array to Spring not good idea, becouse in Spring I will must use more code (split , new String, etc.)
function sendCustomerInfo() {
var nameCustomerForSend = $("#NickNameCustomerForSend").val();
var phoneCustomerForSend = $("#PhoneCustomerForSend").val();
var emailCustomerForSend = $("#EmailCustomerForSend").val();
var addressCustomerForSend = $("#descriptionCustomerForSend").val();
console.log("Name: " + nameCustomerForSend + " Address: " + addressCustomerForSend + " Phone: " + phoneCustomerForSend
+ " Email: " + emailCustomerForSend);
$.ajax({
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
type: "POST", //это типа method
data: {NickName:nameCustomerForSend, Phone:phoneCustomerForSend, Email:emailCustomerForSend,
description:addressCustomerForSend},
url: '/showAll/customerInfo',
success: function (msg) {
window.location.href = "/showAll"
}
});
}
I receive: Failed to load resource: the server responded with a status of 401 ()
In Spring I try to receive:
#RequestMapping(value = "/showAll/customerInfo", method = { RequestMethod.POST}
, produces = MediaType.APPLICATION_JSON_VALUE)
public ModelAndView showAllForCustomer(#RequestParam(value = "NickName")String name,
#RequestParam(value = "Phone")String phone,
#RequestParam(value = "description")String addressDelivery,
#RequestParam(value = "Email")String email) {
System.out.println("Name: " + name + " Phone: " + phone + " Address: " + addressDelivery + " Email: " + email);
ModelAndView modelAndView = new ModelAndView();
return modelAndView;
}
Use #RequestBody with post and application/json type data
Create DTO having all parameter as you specified in showAllForCustomer
like
public ModelAndView showAllForCustomer(#RequestBody CustomerDto dto){
............
}

Ajax Json calling MVC4 Controller Method Parameter Always Null

I am using Ajax with MVC4 web application. I've got a problem with passing values to action method. It's always pass the null as the parrameter value.
Here is my codes.
function onChange(arg) {
var adrId = $.map(this.select(), function (item)
{
return $(item).find('td').first().text();
});
GetEntries(adrId);//Calling the function
}
function GetEntries(adrId) {
//alert("AdrId >> "+adrId); here it shows value is 3465
$.ajax({
url: 'Customer/LoadCustomer',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ adrId: adrId }),
success: function (result) {
alert("success");
}
});
}
[HttpPost]
public JsonResult LoadCustomer(string adrId)//HERE value is ALLWAYS NULL.. :(
{
Address_SelectW adrList = new Address_SelectW();
adrList = this.commonObj.CustomersSelectByAdrKy(cky, usrKy, AdrKy);
return Json(adrList, JsonRequestBehavior.AllowGet);
}
Please help me to solve this problem. Thank you.. :)
===========================================================================
Additional Informations....
I have used another one to insert data. it's worked fine..
$("#btnSave").click(function () {
//var ContactID = $("#txtContactId").val();
var Company = $("#txtCompany").val();
var Status = $("#cmbStatus").val();
var IsActive = $("#IsActive").is(':checked');
var Comments = $("#txaComments").val();
var Country = $("#cmbCountry").val();
var Address1 = $("#txtAddress1").val();
//var Address2 = $("#txtAddress2").val();
var City = $("#txtCity").val();
var State = $("#txtState").val();
var PostalCode = $("#txtPostalCode").val();
var VatNo = $("#txtVatNo").val();
var RegNo = $("#txtRegNo").val();
var Phone = $("#txtPhone").val();
var Email = $("#txtEmail").val();
var AdrKey = $("#AdrID").val();
$.ajax({
url: "Customer/InsertCustomer",
data: {
//'ContactID': ContactID,
'Company': Company,
'Status': Status,
'IsActive': IsActive,
'Comments': Comments,
'Country': Country,
'Address1': Address1,
//'Address2': Address2,
'City': City,
'State': State,
'PostalCode': PostalCode,
'VatNo': VatNo,
'RegNo': RegNo,
'Phone': Phone,
'Email': Email
},
dataType: "json",
type: 'POST',
success: function (data) {
alert("Successfully Inserted!");
},
error: function () {
alert("error");
}
});
});
[HttpPost]
public ActionResult InsertCustomer(string Company, int Status, bool IsActive, string Comments, int Country, string Address1, string City, string State, string PostalCode, string VatNo, string RegNo, string Phone, string Email)
{
AdrCustomModel model = new AdrCustomModel();
bool process = false;
model.Company = Company;
model.Status = Status;
model.IsActive = IsActive;
model.Comments = Comments;
model.Country = Country;
model.Address1 = Address1;
model.City = City;
model.State = State;
model.PostalCode = PostalCode;
model.VatNo = VatNo;
model.Phone = Phone;
model.RegNo = RegNo;
model.Email = Email;
model.cky = cky;
model.ContactID = this.CustomerID(Status);
process = this.commonObj.InsertAdrCustomer(model,usrKy);
Accounts_Select accmodel = new Accounts_Select();
accmodel.CKy = cky;
accmodel.AccCd = model.ContactID;
accmodel.AccNm = Company;
accmodel.AccTypKy = this.commonObj.AccTypeKyByPrefixKy(Status);
process = this.commonObj.InsertAccount(accmodel, usrKy);
return Json(process, JsonRequestBehavior.AllowGet);
}
I have no idea about why this one is working fine and that one is not working. I have tried both JsonResult and ActionResult to Action method. And also tried with and without [HttpPost].
But always Parrameter value is NULL
I'm not sure if it will solve your problem but you can try this.
Place [WebMethod] attribute in your controller method.
or you can you can pass url with appended id like
'Customer/LoadCustomer'+ adrId
Put the property name in quotes:
data: JSON.stringify({ 'adrId': adrId }),
In your first example, you send a JSON object, in the second you just post data.
JSON is unnecessarily complicated to send just one value. Try this instead:
$.ajax({
url: 'Customer/LoadCustomer',
type: 'POST',
data: {'adrId': adrId },
dataType: 'json',
success: function (result) {
alert("success");
}
});
It required concatenate "" with the parameter which you wanna pass to Action method.
function GetEntries(adrId) {
var NewAdrId = ""+adrId; //<<<<<<<<<<<< Answer<<<<<<<<<<<<<<
$.ajax({
url: 'Customer/LoadCustomer',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ adrId: NewAdrId }),
success: function (result) {
alert("success");
}
});
}
// Thanks :)

Sending other data besides File in Ajax Post in Spring MVC

I am trying to send some other data with the file in ajax post
var fileInput = document.getElementById('file');
var creditcardid = document.getElementById('creditcardid');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('creditcardid', 'creditcardid');
formData.append('file', file);
$.ajax({
url: url,
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(response) {
document.getElementById('statusMsg').innerHTML="<fmt:message key="fileUpload.success"/>";
Success();
}
In controller i am writing the code as
#RequestMapping(value = "/fileUpload", method = RequestMethod.POST)
public #ResponseBody String fileUpload(#RequestParam(value = "creditcardid")Long creditcardid,#RequestParam(value = "file") MultipartFile file,Model model, HttpServletRequest request) {
String response = "generic.unexpectederror";
try {
model.addAttribute("message", "File '" + file.getOriginalFilename() + "' uploaded successfully");
logger.info("Size of the file is " + file.getSize());
logger.info("Name of the file is " + file.getOriginalFilename());
response = "fileUpload.success";
} catch (DataIntegrityViolationException e) {
response = "fileUpload.error";
logger.error(ExceptionUtils.getStackTrace(e));
}
return response;
}
But my code is not calling controller. Please let me know how to receive both the data and the file. Thanks

Resources