如何在MVC5中使用ajax请求正确发送__RequestVerificationToken

时间:2015-06-18 01:11:26

标签: ajax asp.net-mvc asp.net-mvc-5

我正在尝试向我的应用程序发送ASP.NET AJAX请求。在应用程序的控制器中,我有:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "ID,Name,Instructions,Glass,Notes")] Drink drink,
    [Bind(Include= "ID,Amount,Brand,IngredientID,DrinkID")] IEnumerable<DrinkIngredient> DrinkIngredients)
{
    if (ModelState.IsValid)
    {
//and so on

我的javascript看起来像这样:

console.log($('#editDrinkForm').serialize())
var x = new XMLHttpRequest();
x = $.post(window.location,
    {
        data: $('#editDrinkForm').serialize()
    })
.done(function () {
    console.log("done");
})
.fail(function () {
    console.log(x.responseText);
})

然而,我看到了这个输出: is too!

您会注意到__RequestVerificationToken是第一个值!那是什么给出了什么?

其他一切

输出转录(从后来的运行)

"__RequestVerificationToken=ZxW-JtClcOb-vYXDarYGYAEXtY84LzeiigiOKRhg4-sLSd1ixS4rwPtU-prisQ_D_vmoOYKP6cZ38ZTn5lhyg8Sh7V_F2VOgve6FkGNDOWcJy8JL8tEwPS7gy8uPd6Xl1_K8VdmWh6UGJBp372w8_w2&ID=1&Name=7%267&DrinkIngredients.index=3&DrinkIngredients%5B3%5D.ID=3&DrinkIngredients%5B3%5D.DrinkID=1&DrinkIngredients%5B3%5D.DrinkIngredientID=3&DrinkIngredients%5B3%5D.Brand=Seagram's+7+crown&DrinkIngredients%5B3%5D.ingredientID=2&DrinkIngredients%5B3%5D.Amount=1+part&DeleteDrinkIngredients.index=3&DrinkIngredients.index=4&DrinkIngredients%5B4%5D.ID=4&DrinkIngredients%5B4%5D.DrinkID=1&DrinkIngredients%5B4%5D.DrinkIngredientID=4&DrinkIngredients%5B4%5D.Brand=7-up&DrinkIngredients%5B4%5D.ingredientID=1&DrinkIngredients%5B4%5D.Amount=4+parts&DeleteDrinkIngredients.index=4&Instructions=combine%2C+stir&Glass=&Notes=fff"

(和)

"<!DOCTYPE html>

<html>

    <head>

        <title>The required anti-forgery form field &quot;__RequestVerificationToken&quot; is not present.</title>

        <meta name="viewport" content="width=device-width" />

        <style>

         body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} 

         p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}

         b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}

         H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }

         H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }

         pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}

         .marker {font-weight: bold; color: black;text-decoration: none;}

         .version {color: gray;}

         .error {margin-bottom: 10px;}

         .expandable { text-decoration:underline; font-weight:bold; color:"[…]

1 个答案:

答案 0 :(得分:0)

x = $.post(window.location, {data: $('#editDrinkForm').serialize()})

错了。这样做:

x = $.post(window.location, data: $('#editDrinkForm').serialize())

(斯蒂芬的一些评论)

相关问题