2

In my controller,

  [HttpPost]
        [OutputCache(CacheProfile = "Short", VaryByParam = "id", VaryByCustom = "none")]
        [ValidateAntiForgeryToken(Salt = @ApplicationEnvironment.SALT)]
        public ActionResult username(string id) {
            try {
                if (id == null || id.Length < 3)
                    return Json(false, JsonRequestBehavior.AllowGet);

                var member = Membership.GetUser(id);

                if (member == null) {
                    //string userPattern = @"^([a-zA-Z])[a-zA-Z_-]*[\w_-]*[\S]$|^([a-zA-Z])[0-9_-]*[\S]$|^[a-zA-Z]*[\S]$";
                    string userPattern = "[A-Za-z][A-Za-z0-9._]{5,14}";
                    if (Regex.IsMatch(id, userPattern))
                        return Json(true, JsonRequestBehavior.AllowGet);
                }

            } catch (Exception ex) {
                CustomErrorHandling.HandleErrorByEmail(ex, "Validate LogName()");
                return Json(false, JsonRequestBehavior.AllowGet);
            }
            //found e false
            return Json(false, JsonRequestBehavior.AllowGet);

        }

and in my view I am doing this for post, I was able to retrieve data for getJSON using HTTP Get. The problem is, when the user puts a space in the name, it doesn't validate and gives a 404. So I thought I could do this using the post method, but it seems that I am unable to send my logname because I am sending an Antiforgery token in the data by serializing it ...

Can any one please help? I would be grateful.

@{
    string SALT = ApplicationEnvironment.SALT;
}

<script type="text/javascript" defer="defer">
    $(function () { 
        if($("#LogName").length > 0){

            $("#LogName").blur(function(){
                var logValidate = "/Validation/username/" + $("#LogName").val();
                //anti-forgery token works don't need to create the input field here but if I pass the logname into the form as an input then if a user puts double quote/single quote then it will also crash.. so is there any other way around. 
                var data = $('<form>@Html.AntiForgeryToken(SALT)</form>').serialize();
                $.post(logValidate, data, function (json) {
                    alert(json);
                });
            });
            $("#Email").blur(function(){
                var emailValidate = "/Validation/email/" + $("#Email").val();

                alert("got it");
            });
        }
    });
</script>
user1542653
  • 439
  • 2
  • 6
  • 16

1 Answers1

0

How about you take the value of the antiforgery token by jquery when sending the request? Generate your antiforgery key as a hidden field:

@Html.AntiForgeryToken()

Look at the sourcecode and adjust the "#__RequestVerificationToken" selector

var antiForgeryVal = $('#__RequestVerificationToken').val();
data["__RequestVerificationToken"] = antiForgeryVal ;
$.post(logValidate, data, function (json) {
    alert(json);
});
Vojtech B
  • 2,837
  • 7
  • 31
  • 59