2

MVC 4 Visual Studio 2012 を使用して Json をコントローラーに投稿しています... JSON データを AntiForgeryToken と共にコントローラーに渡すことに成功しましたが、「AntiForgeryToken の正確性」が実際に機能しているかどうかを正確にテストする方法がわかりません。また、クライアント側の__RequestVerificationTokenコードに9999を追加して、サーバー側で検証されるかどうかを確認しようとしました!!!. 私の推測では、私が正しければ、そうすべきではありません???? ここに私のコードがあります

<script type="text/javascript">

$(document).ready(function (options) {
    $('#id_login_submit').click(function () {

        var token = $('input[name=__RequestVerificationToken]').val();

//var token = $('input[name=__RequestVerificationToken]').val()+"99999";
//   alert("token :: "+token);

        var _authetication_Data = { _UserName: $('#u1').val(), _Password: $('#p1').val(), "__RequestVerificationToken": token }


            $.ajax({
                type: "POST",
                url: "/Account/ProcessLoginRequest",
                data: JSON.stringify({ model: _authetication_Data }),
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (response) {
                    alert(response);
                }
            });

    });
});

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

    @Html.LabelFor(m => m._UserName)
    @Html.TextBoxFor(m => m._UserName, new { id = "u1"})


    @Html.LabelFor(m => m._Password)
    @Html.PasswordFor(m => m._Password, new { id = "p1"})


    <input type="button" id="id_login_submit" value="Login" />
}

   [HttpPost]
   [ValidateAntiForgeryToken]
    public JsonResult ProcessLoginRequest(LoginModel model)
    {
        string returnString = null;


      if (ModelState.IsValid && WebSecurity.Login(model._UserName, model._Password, persistCookie: false))
        {
            returnString = "user is authenticated";     
        }

        else
        { returnString = "user not authenticated"; }

        return Json(returnString, JsonRequestBehavior.AllowGet);
    }
4

2 に答える 2

1

はい、できます...しかし、serialize()メソッドを使用してみることができます。このようなもの:

$.ajax({
                type: "POST",
                url: "/Account/ProcessLoginRequest",
                data: $("#your_form_id").serialize(),
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function (response) {
                    alert(response);
                }
            });

メソッドを使用serializeすると、これはタグ内のすべての要素formを取得し、のようなデータの配列にシリアル化します{ field: value, field2: value2, field3: value3 }。トークンは非表示の入力になるため、シリアル化の結果になります。

詳細については、ドキュメントをご覧ください: http://api.jquery.com/serialize/

于 2012-12-16T16:56:23.707 に答える