SORU
23 Ocak 2013, ÇARŞAMBA


ajax post ASP.NET MVC antiforgerytoken vardır

Ajax ile AntiForgeryToken ile sorun yaşıyorum. ASP.NET MVC 3 kullanıyorum. jQuery Ajax calls and the Html.AntiForgeryToken() çözüm çalıştım. Bu çözümü kullanarak, jeton şimdi geçti:

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) {
            ...
        }
    });

Ben denetleyicisi için [ValidateAntiForgeryToken] sadece verileri (belirteç) parametre olarak geçirilen olup olmadığını görmek için öznitelik kaldırdığınızda, geçirilen olduklarını görebiliyorum. Ama nedense A required anti-forgery token was not supplied or was invalid. mesaj hala özniteliği geri koydum ne zaman açılır.

Herhangi bir fikir?

EDİT

Bu antiforgerytoken bir form içinde üretiliyor, ama aksiyon gönder göndermek için kullanıyorum. Bunun yerine, sadece token değerini jquery kullanarak ve sonra ajax post için çalıştığını anladım.

Burada belirteç içerir ve üst ana sayfasında bulunan formu:

<form id="__AjaxAntiForgeryForm" action="#" method="post">
    @Html.AntiForgeryToken()
</form>

CEVAP
23 Ocak 2013, ÇARŞAMBA


Yanlış application/json contentType belirttiniz.

İşte bu işe yarayabilir bir örnek.

Denetleyici:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Index(string someValue)
    {
        return Json(new { someValue = someValue });
    }
}

Görünüm:

@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>

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • Awesomesauce Network

    Awesomesauce

    4 EKİM 2012
  • Kap Slap

    Kap Slap

    8 Mart 2010
  • New Scientist

    New Scientis

    27 Kasım 2006