I am trying to upload an image file from a partial view using AJAX but it is returning a Bad Request(400) error. I have searched SO answers but it is not working. Here is my script :
$("#prodImgUpload").change(function() {
var formData = new FormData();
formData.append("file", $("#prodImgUpload")[0].files[0]);
console.log(formData.get("file"));
addAntiForgeryToken(formData);
$.ajax({
type: "POST",
url: "#Url.Action("UploadImage","Product",new{area="admin"})",
data: formData,
processData: false,
contentType: false,
cache: false,
async: false,
success: function(result) {
alert("Image uploaded successfully");
},
error: function(jqXHR, textStatus, errorMessage) {
alert(errorMessage);
}
});
And here is the HTML :
<div class="upload-button">
<div class="label">Upload image</div>
<input asp-for="FileToUpload" id="prodImgUpload" name="FileToUpload"
type="file" accept="image/jpeg, image/png, image/jpg, image/bmp" />
</div>
It never reaches the controller. And remember it is in partial view.
Here's my controller's action :
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult UploadImage(IFormFile file)
{
if (file == null)
return Json(new { success = false, message = "No file uploaded" });
//do something with file.
}
You're not including the antiforgery token with the AJAX request. Reference the documentation for how to handle AJAX request with antiforgery tokens. Essentially, you need to add a header to your AJAX request:
$.ajax({
...
headers: {
"RequestVerificationToken": $('#RequestVerificationToken').val()
},
The value comes from a hidden input added via:
#inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf
#functions{
public string GetAntiXsrfRequestToken()
{
return Xsrf.GetAndStoreTokens(Context).RequestToken;
}
}
<input type="hidden" id="RequestVerificationToken"
name="RequestVerificationToken" value="#GetAntiXsrfRequestToken()">
I am having trouble with the AntiForgeryToken with ajax. I'm using ASP.NET MVC 3. I tried the solution in jQuery Ajax calls and the Html.AntiForgeryToken(). Using that solution, the token is now being passed:
var data = { ... } // with token, key is '__RequestVerificationToken'
$.ajax({
type: "POST",
data: data,
datatype: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
url: myURL,
success: function (response) {
...
},
error: function (response) {
...
}
});
When I remove the [ValidateAntiForgeryToken] attribute just to see if the data (with the token) is being passed as parameters to the controller, I can see that they are being passed. But for some reason, the A required anti-forgery token was not supplied or was invalid. message still pops up when I put the attribute back.
Any ideas?
EDIT
The antiforgerytoken is being generated inside a form, but I'm not using a submit action to submit it. Instead, I'm just getting the token's value using jquery and then trying to ajax post that.
Here is the form that contains the token, and is located at the top master page:
<form id="__AjaxAntiForgeryForm" action="#" method="post">
#Html.AntiForgeryToken()
</form>
You have incorrectly specified the contentType to application/json.
Here's an example of how this might work.
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(string someValue)
{
return Json(new { someValue = someValue });
}
}
View:
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "__AjaxAntiForgeryForm" }))
{
#Html.AntiForgeryToken()
}
<div id="myDiv" data-url="#Url.Action("Index", "Home")">
Click me to send an AJAX request to a controller action
decorated with the [ValidateAntiForgeryToken] attribute
</div>
<script type="text/javascript">
$('#myDiv').submit(function () {
var form = $('#__AjaxAntiForgeryForm');
var token = $('input[name="__RequestVerificationToken"]', form).val();
$.ajax({
url: $(this).data('url'),
type: 'POST',
data: {
__RequestVerificationToken: token,
someValue: 'some value'
},
success: function (result) {
alert(result.someValue);
}
});
return false;
});
</script>
Another (less javascriptish) approach, that I did, goes something like this:
First, an Html helper
public static MvcHtmlString AntiForgeryTokenForAjaxPost(this HtmlHelper helper)
{
var antiForgeryInputTag = helper.AntiForgeryToken().ToString();
// Above gets the following: <input name="__RequestVerificationToken" type="hidden" value="PnQE7R0MIBBAzC7SqtVvwrJpGbRvPgzWHo5dSyoSaZoabRjf9pCyzjujYBU_qKDJmwIOiPRDwBV1TNVdXFVgzAvN9_l2yt9-nf4Owif0qIDz7WRAmydVPIm6_pmJAI--wvvFQO7g0VvoFArFtAR2v6Ch1wmXCZ89v0-lNOGZLZc1" />
var removedStart = antiForgeryInputTag.Replace(#"<input name=""__RequestVerificationToken"" type=""hidden"" value=""", "");
var tokenValue = removedStart.Replace(#""" />", "");
if (antiForgeryInputTag == removedStart || removedStart == tokenValue)
throw new InvalidOperationException("Oops! The Html.AntiForgeryToken() method seems to return something I did not expect.");
return new MvcHtmlString(string.Format(#"{0}:""{1}""", "__RequestVerificationToken", tokenValue));
}
that will return a string
__RequestVerificationToken:"P5g2D8vRyE3aBn7qQKfVVVAsQc853s-naENvpUAPZLipuw0pa_ffBf9cINzFgIRPwsf7Ykjt46ttJy5ox5r3mzpqvmgNYdnKc1125jphQV0NnM5nGFtcXXqoY3RpusTH_WcHPzH4S4l1PmB8Uu7ubZBftqFdxCLC5n-xT0fHcAY1"
so we can use it like this
$(function () {
$("#submit-list").click(function () {
$.ajax({
url: '#Url.Action("SortDataSourceLibraries")',
data: { items: $(".sortable").sortable('toArray'), #Html.AntiForgeryTokenForAjaxPost() },
type: 'post',
traditional: true
});
});
});
And it seems to work!
it is so simple! when you use #Html.AntiForgeryToken() in your html code it means that server has signed this page and each request that is sent to server from this particular page has a sign that is prevented to send a fake request by hackers. so for this page to be authenticated by the server you should go through two steps:
1.send a parameter named __RequestVerificationToken and to gets its value use codes below:
<script type="text/javascript">
function gettoken() {
var token = '#Html.AntiForgeryToken()';
token = $(token).val();
return token;
}
</script>
for example take an ajax call
$.ajax({
type: "POST",
url: "/Account/Login",
data: {
__RequestVerificationToken: gettoken(),
uname: uname,
pass: pass
},
dataType: 'json',
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
success: successFu,
});
and step 2 just decorate your action method by [ValidateAntiForgeryToken]
In Asp.Net Core you can request the token directly, as documented:
#inject Microsoft.AspNetCore.Antiforgery.IAntiforgery Xsrf
#functions{
public string GetAntiXsrfRequestToken()
{
return Xsrf.GetAndStoreTokens(Context).RequestToken;
}
}
And use it in javascript:
function DoSomething(id) {
$.post("/something/todo/"+id,
{ "__RequestVerificationToken": '#GetAntiXsrfRequestToken()' });
}
You can add the recommended global filter, as documented:
services.AddMvc(options =>
{
options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
})
Update
The above solution works in scripts that are part of the .cshtml. If this is not the case then you can't use this directly. My solution was to use a hidden field to store the value first.
My workaround, still using GetAntiXsrfRequestToken:
When there is no form:
<input type="hidden" id="RequestVerificationToken" value="#GetAntiXsrfRequestToken()">
The name attribute can be omitted since I use the id attribute.
Each form includes this token. So instead of adding yet another copy of the same token in a hidden field, you can also search for an existing field by name. Please note: there can be multiple forms inside a document, so name is in that case not unique. Unlike an id attribute that should be unique.
In the script, find by id:
function DoSomething(id) {
$.post("/something/todo/"+id,
{ "__RequestVerificationToken": $('#RequestVerificationToken').val() });
}
An alternative, without having to reference the token, is to submit the form with script.
Sample form:
<form id="my_form" action="/something/todo/create" method="post">
</form>
The token is automatically added to the form as a hidden field:
<form id="my_form" action="/something/todo/create" method="post">
<input name="__RequestVerificationToken" type="hidden" value="Cf..." /></form>
And submit in the script:
function DoSomething() {
$('#my_form').submit();
}
Or using a post method:
function DoSomething() {
var form = $('#my_form');
$.post("/something/todo/create", form.serialize());
}
In Asp.Net MVC when you use #Html.AntiForgeryToken() Razor creates a hidden input field with name __RequestVerificationToken to store tokens. If you want to write an AJAX implementation you have to fetch this token yourself and pass it as a parameter to the server so it can be validated.
Step 1: Get the token
var token = $('input[name="`__RequestVerificationToken`"]').val();
Step 2: Pass the token in the AJAX call
function registerStudent() {
var student = {
"FirstName": $('#fName').val(),
"LastName": $('#lName').val(),
"Email": $('#email').val(),
"Phone": $('#phone').val(),
};
$.ajax({
url: '/Student/RegisterStudent',
type: 'POST',
data: {
__RequestVerificationToken:token,
student: student,
},
dataType: 'JSON',
contentType:'application/x-www-form-urlencoded; charset=utf-8',
success: function (response) {
if (response.result == "Success") {
alert('Student Registered Succesfully!')
}
},
error: function (x,h,r) {
alert('Something went wrong')
}
})
};
Note: The content type should be 'application/x-www-form-urlencoded; charset=utf-8'
I have uploaded the project on Github; you can download and try it.
https://github.com/lambda2016/AjaxValidateAntiForgeryToken
function DeletePersonel(id) {
var data = new FormData();
data.append("__RequestVerificationToken", "#HtmlHelper.GetAntiForgeryToken()");
$.ajax({
type: 'POST',
url: '/Personel/Delete/' + id,
data: data,
cache: false,
processData: false,
contentType: false,
success: function (result) {
}
});
}
public static class HtmlHelper
{
public static string GetAntiForgeryToken()
{
System.Text.RegularExpressions.Match value = System.Text.RegularExpressions.Regex.Match(System.Web.Helpers.AntiForgery.GetHtml().ToString(), "(?:value=\")(.*)(?:\")");
if (value.Success)
{
return value.Groups[1].Value;
}
return "";
}
}
In Account controller:
// POST: /Account/SendVerificationCodeSMS
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public JsonResult SendVerificationCodeSMS(string PhoneNumber)
{
return Json(PhoneNumber);
}
In View:
$.ajax(
{
url: "/Account/SendVerificationCodeSMS",
method: "POST",
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
dataType: "json",
data: {
PhoneNumber: $('[name="PhoneNumber"]').val(),
__RequestVerificationToken: $('[name="__RequestVerificationToken"]').val()
},
success: function (data, textStatus, jqXHR) {
if (textStatus == "success") {
alert(data);
// Do something on page
}
else {
// Do something on page
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus);
console.log(jqXHR.status);
console.log(jqXHR.statusText);
console.log(jqXHR.responseText);
}
});
It is important to set contentType to 'application/x-www-form-urlencoded; charset=utf-8' or just omit contentTypefrom the object ...
I know this is an old question. But I will add my answer anyway, might help someone like me.
If you dont want to process the result from the controller's post action, like calling the LoggOff method of Accounts controller, you could do as the following version of #DarinDimitrov 's answer:
#using (Html.BeginForm("LoggOff", "Accounts", FormMethod.Post, new { id = "__AjaxAntiForgeryForm" }))
{
#Html.AntiForgeryToken()
}
<!-- this could be a button -->
Submit
<script type="text/javascript">
$('#ajaxSubmit').click(function () {
$('#__AjaxAntiForgeryForm').submit();
return false;
});
</script>
For me the solution was to send the token as a header instead of as a data in the ajax call:
$.ajax({
type: "POST",
url: destinationUrl,
data: someData,
headers:{
"RequestVerificationToken": token
},
dataType: "json",
success: function (response) {
successCallback(response);
},
error: function (xhr, status, error) {
// handle failure
}
});
The token won't work if it was supplied by a different controller. E.g. it won't work if the view was returned by the Accounts controller, but you POST to the Clients controller.
I tried a lot of workarrounds and non of them worked for me. The exception was "The required anti-forgery form field "__RequestVerificationToken" .
What helped me out was to switch form .ajax to .post:
$.post(
url,
$(formId).serialize(),
function (data) {
$(formId).html(data);
});
Feel free to use the function below:
function AjaxPostWithAntiForgeryToken(destinationUrl, successCallback) {
var token = $('input[name="__RequestVerificationToken"]').val();
var headers = {};
headers["__RequestVerificationToken"] = token;
$.ajax({
type: "POST",
url: destinationUrl,
data: { __RequestVerificationToken: token }, // Your other data will go here
dataType: "json",
success: function (response) {
successCallback(response);
},
error: function (xhr, status, error) {
// handle failure
}
});
}
Create a method that will responsible to add token
var addAntiForgeryToken = function (data) {
data.__RequestVerificationToken = $("[name='__RequestVerificationToken']").val();
return data;
};
Now use this method while passing data/parameters to Action like below
var Query = $("#Query").val();
$.ajax({
url: '#Url.Action("GetData", "DataCheck")',
type: "POST",
data: addAntiForgeryToken({ Query: Query }),
dataType: 'JSON',
success: function (data) {
if (data.message == "Success") {
$('#itemtable').html(data.List);
return false;
}
},
error: function (xhr) {
$.notify({
message: 'Error',
status: 'danger',
pos: 'bottom-right'
});
}
});
Here my Action have a single parameter of string type
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult GetData( string Query)
{
#using (Ajax.BeginForm("SendInvitation", "Profile",
new AjaxOptions { HttpMethod = "POST", OnSuccess = "SendInvitationFn" },
new { #class = "form-horizontal", id = "invitation-form" }))
{
#Html.AntiForgeryToken()
<span class="red" id="invitation-result">#Html.ValidationSummary()</span>
<div class="modal-body">
<div class="row-fluid marg-b-15">
<label class="block">
</label>
<input type="text" id="EmailTo" name="EmailTo" placeholder="forExample#gmail.com" value="" />
</div>
</div>
<div class="modal-footer right">
<div class="row-fluid">
<button type="submit" class="btn btn-changepass-new">send</button>
</div>
</div>
}
I am new here. Would like to seek your help for the problem that blocks me several days.
The design is simple. I have a server.js running localhost. It provides a POST (Login to acquire authentication) and a GET method (retrieving json after authentication). The login uses basic authentication to verify email/password of a user. if matches, return status 200 and put the user in the session & response. The following are the server side codes:
//Log user in Server.js
app.post('/session/login', function(req, res) {
var email = req.body.email;
var password = req.body.password;
if ( null == email || email.length < 1
|| null == password || password.length < 1 ) {
res.status(401).send("Wrong username or password");
return;
}
if (email == "xxxxx" && password == "xxxxx") {
var user = new User(email, password);
req.session.user = user;
return res.status(200).send({
auth : true,
user : user
});
}else{
return res.status(401).send("Wrong username or password");
}
});
The Get Method is having a basic auth before server can pass the json back. The following are the codes:
function Auth (req, res, next) {
if(req.session.user){
next();
}else{
console.log("Auth");
res.status(401).send({
flash : 'Please log in first'
});
}
}
app.get('/form/FormFields', Auth, function(req, res) {
fs.readFile(FORMFIELDS_FILE, function(err, data) {
if (err) {
console.error(err);
process.exit(1);
}
res.json(JSON.parse(data));
});
});
Now client side, I have two js files, one is a form to email/password to call Login above, and the other is simply get the form info using ajax in react. The navigation uses React-Router. The following are some codes:
// login.js
var LoginBox = React.createClass({
getInitialState: function () {
return {text: '', data: []};
},
handleLoginSubmit: function (data) {
$.ajax({
url: "https://localhost:3000/session/login",
dataType: 'json',
type: 'POST',
data: data,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
render: function () {
return(
<div className="container">
<LoginForm data={this.state.data} onLoginSubmit={this.handleLoginSubmit} />
<p className="tips">{this.state.text}</p>
</div>
);
}
});
var LoginForm = React.createClass({
contextTypes: {
router: React.PropTypes.object
},
getInitialState: function () {
return {data:0,tittle: 'Login Test',text:''};
},
handleSubmit: function (e) {
e.preventDefault();
var email = this.refs.email.value.trim();
var password = this.refs.password.value.trim();
if (!email || !password) {
this.setState({text:"please input both username and password!"});
return;
}
this.props.onLoginSubmit({email:email,password:password});
this.setState({text:""});
this.refs.email.value = '';
this.refs.password.value = '';
//Routing defined in React-Router
const path = '/form';
this.context.router.push(path);
},
render: function () {
return (
<form className="loginForm" onSubmit={this.handleSubmit}>
<p>{this.state.tittle}</p>
<input type="email" placeholder="Your username" ref="email"/>
<input type="password" placeholder="Your password" ref="password"/>
<input type="submit" value="Login"/>
<p className="tips">{this.state.text}</p>
</form>
)
}
});
//code piece in form.js to call server and get form info
loadFieldsFromServer: function() {
$.ajax({
url: "https://localhost:3000/form/FormFields",
dataType: 'json',
cache: false,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
Eventually, here is my problem. the login is ok, which I can see from network monitoring. I printed the log in server and found user is saved in the session. However when it navigates to form.js, I always retrieve 401 from server code below. from the log, i found user info in the session disappears and hence the following 401 returns.
else{
console.log("Auth");
res.status(401).send({
flash : 'Please log in first'
});
}
Please anybody help take a look at where i am wrong. Many thanks. BTW, just share more info, when I use Postman to simulate two calls to the server. Once I call login first, I can also retrieve form json successfully unless i call logout to clean the user in the session. Just dont know why it does not work in the program.
I am working on as asp.net application. Its view has a button like this:
<input type="button" id="btnCall" title="Call" value="Call" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" />
and in document.ready, I have this:
$("#btnCall").click(function () {
alert("here");
$.ajax({
type: "POST",
dataType: "text/json",
url: "/account/getGenericPassword",
success: function (data) {
alert("data" + data);
if (data == null || data == "") {
alert("Generic Password is empty. Please enter generic password");
}
else {
//saveCallRecording();
}
}
});
});
and method is like this:
[Authorize]
public JsonResult GetGenericPassword() {
using (IUserProfileManager profilemanager = new ManagerFactory().GetUserProfileManager()) {
UserProfile profile = profilemanager.GetProfile(CurrentUser.Id, CurrentAccount.Id);
return Json(profile.GenericPassword == null ? "" : profile.GenericPassword, JsonRequestBehavior.AllowGet);
}
}
but alert in success is not shown. Please suggest solution.
Try setting the dataType like so:
dataType: "json"
See the valid dataType options at http://api.jquery.com/jQuery.ajax/
try with these
type:'Post',
url:'#Url.Action("actionname","controller")',
datatype:"json",
data:{},
success:function(data){
}
I am trying to register a user via AJAX using FOSUserBundle.
The problem is that the name value in the form is fos_user_registration_form_[username] so it isn't accepted by javascript as array.
<input type="text" id="fos_user_registration_form_username" name="fos_user_registration_form[username]" required="required" />
How can I solve that?
Can I change the name parameter in FOSUserBUndle to fos_user_registration_form_username ?
How can I create an array with fos_user_registration_form_[username] value in Javascript?
$("#registerButton").click( function(){
data = {
fos_user_registration_form_[username]:$("#name").val(), // HERE IS WHERE IT CRASHES, IN THE [username] field.
fos_user_registration_form_[email]:$("#email").val(),
fos_user_registration_form_[plainPassword]:$("#password").val(),
};
$.ajax({
type: "POST",
url: serviceURL,
asyn:false,
data: data,
dataType: "json",
success: function(res) {
alert("success"); // JUST FOR TEST
}
});
I am testing a basic example..
This works (triggers the alert)
<script type="text/javascript">
data = {
fos_user_registration_form_username:"blabla"
};
alert(true);
</script>
This doesn't works: (do not trigger the alert)
<script type="text/javascript">
data = {
fos_user_registration_form_[username]:"blabla"
};
alert(true);
</script>
To fetch the data from your input fields, you need to combine the name_of_the_form_ + the name_of_the_field. For example:
fos_user_registration_form_ + username => fos_user_registration_form_username
data = {
fos_user_registration_form[username]:$("#fos_user_registration_form_username").val(),
fos_user_registration_form[email]:$("#fos_user_registration_form_email").val(),
fos_user_registration_form[plainPassword]:$("#fos_user_registration_form_plainPassword").val(),
};