1、 在Startup.cs文件中添加: services.AddMvc();
services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
2、在cshtml 文件中添加:
@Html.AntiForgeryToken()
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
3、前端代码
$('#btnPost').on('click', function () { var item1 = $('#txtItem1').val(); var item2 = $('#txtItem2').val(); $.ajax({ type: "POST", url: "RoleMenu?handler=Send", beforeSend: function (xhr) { xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val()); }, data: JSON.stringify({ id: item1, name: item2, }), contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { var dvItems = $("#dvPostItems"); dvItems.empty(); $.each(response, function (i, item) { var $tr = $('<li>').append(item).appendTo(dvItems); }); }, failure: function (response) { alert(response); } });
后台代码:
public ActionResult OnPostSend() { string sPostValue1 = ""; string sPostValue2 = ""; { MemoryStream stream = new MemoryStream(); Request.Body.CopyTo(stream); stream.Position = 0; using (StreamReader reader = new StreamReader(stream)) { string requestBody = reader.ReadToEnd(); if (requestBody.Length > 0) { var obj = JsonConvert.DeserializeObject<TmpRoleMenu>(requestBody); if (obj != null) { sPostValue1 = obj.id+"postdata"; sPostValue2 = obj.name+"postdata"; } } } } List<string> lstString = new List<string> { sPostValue1, sPostValue2, }; return new JsonResult(lstString); }
参考:
1、http://www.jb51.net/article/133437.htm