Add Required Anti-Forgery Field Ajax Request on MVC - ajax

I'm trying to do an ajax post request on my MVC app, simply post data of form to server.
but I always get this error:
The required anti-forgery form field "__RequestVerificationToken" is not present.
This is my code for ajax request:
var reservationID = document.getElementById('ReservationID').value;
var arrival = document.getElementById('Arrival').value;
var departure = document.getElementById('Departure').value;
var noofrooms = document.getElementById('NoOfRooms').value;
var guestid = document.getElementById('GuestID').value;
var rateid = document.getElementById('RateID').value;
var agencyid = document.getElementById('AgencyID').value;
var sourceid = document.getElementById('SourceID').value;
var reservationtype = document.getElementById('ReservationType').value;
var reservation = { ReservationID: reservationID, Arrival: arrival, Departure: departure, NoOfRooms: noofrooms, GuestID: guestid, RateID: rateid, AgencyID: agencyid, SourceID: sourceid, ReservationTypeID: reservationtype };
var url = '/Reservations/Create';
$.ajax({
url: url,
type: "POST",
data : reservation,
contentType: "application/json; charset=utf-8",
success: function(data, textStatus, jqXHR) {
alert('success');
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
How can I add this anti-forgery field on my ajax?

For me this sollution works:
<script>
#functions{
public string TokenHeaderValue()
{
string cookieToken, formToken;
AntiForgery.GetTokens(null, out cookieToken, out formToken);
return cookieToken + ":" + formToken;
}
}
$.ajax("api/values", {
type: "post",
contentType: "application/json",
data: { }, // JSON data goes here
dataType: "json",
headers: {
'RequestVerificationToken': '#TokenHeaderValue()'
}
});
</script>
taken from:
Preventing Cross-Site Request Forgery (CSRF) Attacks in ASP.NET Web API

Related

How to send post ajax request from (.js) file to Spring MVC Controller?

(.js)
$.ajax({
type: "POST",
//contentType : "application/json",
dataType : "json",
url: "getStateNames",
//url:"http://localhost:8081/Mining_22_11_17/pages/admin/a.jsp",
cache: false,
data: "region=" + re + "& stId=" + state_id,
success: function(response){
//$('#result').html("");
alert("hiiii state list");
var obj = JSON.parse(response);
alert("state list" + obj);
//$('#result').html("First Name:- " + obj.firstName +"</br>Last Name:- " + obj.lastName + "</br>Email:- " + obj.email);
},
error: function(){
alert('Error while request..');
}
});
Spring MVC Controller
#RequestMapping(value="/getStateNames",method = RequestMethod.POST)
public #ResponseBody RegionDistrict add(HttpServletRequest request, HttpServletResponse response,#RequestParam String region, #RequestParam String stId) {
System.out.println("Get state");
}
By running this program I am getting 404 error.I want to send request using POST only.
$("#yourID").click(function(event) {
var region = $('#id').val();
var state_id = $('#edited').val();
$.post("${pageContext.request.contextPath}/getStateNames", {
region : region ,
state_id : state_id
}, function(data) {
//var json = JSON.parse(data);
//...
}).done(function(data) {
alert("hiiii state list");
swal("success");
//location.reload();
}).fail(function(xhr, textStatus, errorThrown) {
}).complete(function() {
//$("#btn-save").prop("disabled", false);
});
});
try this hope its works fine
$.ajax({
type: "POST",
url: "/getStateNames",
data: { region: re, stId: state_id },
success : function(response) {
alert(JSON.stringify(resoinse));
},
error: function(){
alert('Error while request..');
}
});
This should work, tell me if this solves your problem

How to implement Antiforgerytokens with partial views in mvc4?

I am trying to implement antiforgerytoken in my project. I am able to implement it when making ajax call below.
function docDelete(id) {
var _upload_id = $("#docId").val();
var _comments = $("#name").val();
var forgeryId = $("#forgeryToken").val();
$("#dialog-form").dialog("open");
$.ajax({
type: 'GET',
cache: false,
url: '/DeleteDocument/Delete',
dataType: 'json',
headers: {
'VerificationToken': forgeryId
},
data: { _upload_id: _upload_id, _comments: _comments },
success: function (data) {
$('#dialog-form').dialog('close');
$('#name').val('');
$('#dvSuccess').val(data);
Getgridata(data);
}
});
}
above code works fine. But in some cases i am making ajax request as below.
var forgeryId = $("#forgeryToken").val();
function GetGrid() {
$.ajax(
{
type: "GET",
dataType: "html",
cache: false,
url: '/Dashboard/GetGridData',
headers: {
'VerificationToken': forgeryId
},
success: function (data) {
$('#dvmyDocuments').html("");
$('#dvmyDocuments').html(data);
}
});
}
Above code does not send any token to below method.
private void ValidateRequestHeader(HttpRequestBase request)
{
string cookieToken = string.Empty;
string formToken = string.Empty;
string tokenValue = request.Headers["VerificationToken"]; // read the header key and validate the tokens.
if (!string.IsNullOrEmpty(tokenValue))
{
string[] tokens = tokenValue.Split(',');
if (tokens.Length == 2)
{
cookieToken = tokens[0].Trim();
formToken = tokens[1].Trim();
}
}
AntiForgery.Validate(cookieToken, formToken); // this validates the request token.
}
}
In layout.cshtml i have implmented code to get token.
<script>
#functions{
public string GetAntiForgeryToken()
{
string cookieToken, formToken;
AntiForgery.GetTokens(null, out cookieToken, out formToken);
return cookieToken + "," + formToken;
}
}
</script>
<input type="hidden" id="forgeryToken" value="#GetAntiForgeryToken()" />
The variable tokenValue catching null each time. So what i understood is through headers i am not able to send token value. I tried many alternatives. So anyone suggest me how can i overcome this issue? Thank you in advance.
I tried as below still i am getting null value.
var token = $('[name=__RequestVerificationToken]').val();
var headers = {};
headers["__RequestVerificationToken"] = token;
alert(token);
var forgeryId = JSON.stringify($("#forgeryToken").val());
function GetGrid() {
$.ajax(
{
type: "GET",
dataType: "html",
cache: false,
url: '/Dashboard/GetGridData',
cache: false,
headers: headers,
success: function (data) {
$('#dvmyDocuments').html("");
$('#dvmyDocuments').html(data);
}
});
}

Passing more then 1 value to webmethod using FormData via Ajax

I'm trying to pass the uploaded image + two additional parameters to my web service using the FormData method from my Ajax method as shown here:
var formData = new FormData();
formData.append('file', $('#photo')[0].files[0]);
formData.append('u', "test");
formData.append('s', "Testing");
My ajax call is outlined like so:
$.ajax({
url: "/admin/WebService/test.asmx/UploadImage",
type: "POST",
processData: false,
contentType: false,
data: formData,
success: function (response) {
console.log(response);
},
error: function (er) {
alert(er);
}
});
Which calls this webmethod:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string UploadImage()
{
if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
{
var t= System.Web.HttpContext.Current.Request.Files["s"];
var c= System.Web.HttpContext.Current.Request.Files["u"];
var p = System.Web.HttpContext.Current.Request.Files["file"];
}
else
{
return "Error";
}
return "Error";
}
The issue I'm having is the parameters 'u' and 's' are null yet when referencing file I'm able to get its value.
Whilst searching the web I was under the impression you can specify as many key/values are required when using this approach unless I have been misinformed? can someone please shed some light into why these two parameters are null? Thanks in advance.
This works for me:
JavaScript
var formData = new FormData();
formData.append("UserId", userId);
formData.append("RequestPhoto", imageFile);
formData.append("RequestVoiceRecord", voiceFile);
formData.append("Latitude", latitude);
formData.append("Longitude", longtitude);
$.ajax({
type: "POST",
url: "/User/CreateRequest",
data: formData,
contentType: false,
processData: false,
success: function () {
alert("OK");
},
error: function () {
alert("Error");
}
});
Controller:
public class UserController : ApiController
{
[HttpPost]
public int CreateRequest()
{
// HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
var req = new UserRequest
{
UserId = Guid.Parse(httpRequest.Form["UserId"]),
Photo = httpRequest.Files["RequestPhoto"],
VoiceRecord = httpRequest.Files["RequestVoiceRecord"]
Latitude = float.Parse(httpRequest.Form["Latitude"]),
Longitude = float.Parse(httpRequest.Form["Longitude"]),
};
You should create one json instead of create this stuff, add whatever keys you want to sent via ajax.
var formData = {'u':'value','s':'value'}
$.ajax({
url: "/admin/WebService/test.asmx/UploadImage",
type: "POST",
processData: false,
contentType: false,
data: JDON.Stringify(formData),
success: function (response) {
console.log(response);
},
error: function (er) {
alert(er);
}
});
try using this way.

how to get into [FromBody]Guid[] use ajax

I am using WAP API, but don't know how to use ajax connect into the aaa method. Please help. same the ajax method cannot match [FromBody]Guid[] Ids, but how
[Route("aaa")]
[HttpPost]
public IHttpActionResult aaa(Guid teamId, [FromBody]Guid[] Ids)
javascript
var routeIds = new Array();
routeIds.push('EEBEEEDF-41F2-4931-41F2-362DDDDDD06');
routeIds.push('EEBEEEDF-41F2-41F2-41F2-362DDDDDDD06');
routeIds.push('EEBEEEDF-41F2-41F2-41F2-362DDDDDDD06');
routeIds.push('EEBEEEDF-41F2-41F2-41F2-362DDDDDDD06');
var team = { id: "EEBEEEDF-41F2-41F2-41F2-362DDDDDDD06" };
var tmp = JSON.stringify({ teamId: "EEBEEEDF-41F2-41F2-41F2-362DDDDDDD06", '': routeIds });
var path = GlobalData.url + "api/Event/UpdateRouteEnrollments";
$http({
method: 'POST',
url: path,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(tmp)
}).
success(function (data, status, headers, config) {
$scope.hide();
FeedStorage.save({ "id": data.TeamId, "Route": "0CE0F3C9-BB1E-4931-98F3-362DDE7BD406" });
$scope.setPlatform('team');
}).
error(function (data, status, headers, config) {
$scope.hide();
alert('An error occured:' + status);
});

Jquery ajax goes to error even though result came

I am using spring MVC and JQuery ajax. In one of my ajax call it returns large amount of data it nearly takes 5 minutes.
In Ajax method shows error even though the response came i checked it through firebug.
my ajax coding is
jQuery(document).ready(function () {
jQuery("sampleSearch").click(function () {
jQuery("body").addClass("loading");
var formValues = jQuery('#sample-search-form').find(':input[value][value!=""]').serialize();
jQuery.ajax({
type: "GET",
url: "/sample/user-byName",
data: formValues,
dataType: 'json',
success: function (data) {
jQuery('#json').val(JSON.stringify(data)).trigger('change');
jQuery('body').removeClass("loading");
},
error: function (e) {
alert('Error while request..' + e.toLocaleString());
jQuery('body').removeClass("loading");
}
});
});
});
and in my controller
#RequestMapping(value = "/user-byName", method = RequestMethod.GET)
#ResponseStatus(HttpStatus.OK)
public
#ResponseBody
String getUserByName(HttpServletRequest request) {
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
Integer page = Integer.parseInt(request.getParameter("page"));
String resultJson = getUserByName(firstName, lastName, page);
return resultJson;
}
You need to increase the timeout for the request.
jQuery.ajax({
type: "GET",
url: "/sample/user-byName",
data: formValues,
dataType: 'json',
timeout: 600000,
success: function (data) {
jQuery('#json').val(JSON.stringify(data)).trigger('change');
jQuery('body').removeClass("loading");
},
error: function (e) {
alert('Error while request..' + e.toLocaleString());
jQuery('body').removeClass("loading");
}
});
read more in the .ajax() documentation

Resources