【问题标题】:How to call async Task from ajax aspnet core如何从 ajax asp net core 调用异步任务
【发布时间】:2018-01-15 08:12:47
【问题描述】:

我正在使用 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

【问题讨论】:

  • 检查您的浏览器控制台并发布您遇到的控制台错误。
  • 是的,我检查了它是 500 状态码错误
  • 在本地主机中是否点击了操作方法,你想要[ValidateAntiForgeryToken] 吗?
  • 将令牌传递给请求 var form = $('form'); var token = $('input[name="__RequestVerificationToken"]', form).val();数据:{ __RequestVerificationToken:令牌},
  • 我不想使用 [ValidateAntiForgeryToek] 实际上这是我的测试方法,因为它在 IIS 上托管后没有调用。

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


【解决方案1】:

在 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);
}

【讨论】:

    【解决方案2】:

    如果你不想 [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

    【讨论】:

    • 嗨,尼梅什·加米先生,兄弟。我再次在 IIS 上调用该 actionMethod 时遇到问题,但它在本地主机上运行良好。我附上了我的错误图片。请检查一下
    • 欢迎来到 SO,如果您想对 Nimesh Gami 发表评论,请使用@check this 帖子了解如何回复特定用户。遇到您的错误,它会给出 500 错误,因为您使用的是 return NotFound(); 而不是使用 return Ok();
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多