如何从ajax aspnet核心调用异步任务

时间:2018-01-15 08:12:47

标签: asp.net-mvc asp.net-core-mvc asp.net-core-mvc-2.0

我正在使用asp.net核心,我从ajax调用异步任务ActionResult方法。它在本地主机上运行良好,但在IIS上托管后,它会抛出500状态代码错误。

但它不是调用此方法是ajax代码

  

这是ajax方法:

$('.Savebtn').click(function () {
                    $.ajax({
                        url: '@Url.Action("Testing", "Home")',
                        data: "Test data",
                        type: 'POST', //POST if you want to save, GET if you want to fetch data from server
                        success: function (obj) {
                            // here comes your response after calling the server
                            alert('Suceeded');
                        },
                        error: function (obj) {
                            alert('Something happened');
                        }
                    });
            });

这是控制器方法:

   [HttpPost]

   public async Task<IActionResult> Testing()
   {
       if (ModelState.IsValid)
         {
            try
            {
               return NotFound();
            }
            catch (Exception ex)
            {
                return NotFound();
            }

         }
            return View();
   }

Error Screen Shot

2 个答案:

答案 0 :(得分:0)

如果您不希望[ValidateAntiForgeryToken]删除它,它将会有效。如果您需要,则必须传递自动生成的cookie值以进行验证,如下所述,选中this

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Testing()
{
   if (ModelState.IsValid)
    {
      try
      {
        await Task.Delay(100);

        return Ok();
      }
      catch (Exception ex)
      {

       return NotFound();

      }

    }
       return View();
 }

查看:

@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "__AjaxAntiForgeryForm" }))
    {
        @Html.AntiForgeryToken()
    }

    <button class="Savebtn btn btn-success">Save</button>

脚本:

    $(document).ready(function () {


        $('.Savebtn').click(function () {
            var form = $('#__AjaxAntiForgeryForm');
            var token = $('input[name="__RequestVerificationToken"]', form).val();

            $.ajax({
                url: '@Url.Action("Testing", "Home")',
                data: {
                    __RequestVerificationToken: token,
                    data: "Test data"
                },
                type: 'POST', //POST if you want to save, GET if you want to fetch data from server
                success: function (obj) {
                    // here comes your response after calling the server
                    alert('Suceeded');
                },
                error: function (obj) {
                    alert('Something happened');
                }
            });
    });

    })

</script>

Reference

答案 1 :(得分:0)

在Startup.cs文件中添加如下服务:

services.AddAntiforgery(options => options.HeaderName = "RequestVerificationToken");

在您的cshtml文件中添加:

@Html.AntiForgeryToken()

$.ajax({
    type: 'GET',
    url: '/home/Demo1',
    beforeSend: function (xhr) {
        xhr.setRequestHeader("RequestVerificationToken",
            $('input:hidden[name="__RequestVerificationToken"]').val());
    },
    success: function (result) {
        alert(result);
    },
    error: function (xhr, ajaxOptions, thrownError) {
        alert(thrownError);
    }
});

您在Controller中的方法如下:

[HttpGet]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Demo1()
{
    //your code
    return new JsonResult(null);
}