asp net core 5中的Ajax错误请求400

Posted

技术标签:

【中文标题】asp net core 5中的Ajax错误请求400【英文标题】:Ajax in asp net core 5 Bad request 400 【发布时间】:2021-08-18 16:03:58 【问题描述】:

当我尝试在 javascript 中运行函数 ajax 时,出现类似“加载资源失败:服务器响应状态为 400 ()”的错误。该怎么办?请帮帮我!

@page
@model IndexModel
@
    ViewData["Title"] = "Home page";

<div class="container">
<p id="scanned"></p>
</div>
<script type="text/javascript">
        function Q(el) 
            if (typeof el === "string") 
                var els = document.querySelectorAll(el);
                return typeof els === "undefined" ? undefined : els.length > 1 ? els : els[0];
            
            return el;
        
        var txt = "innerText" in htmlElement.prototype ? "innerText" : "textContent";
        var scannedQR = Q("#scanned");
      var args = 
            autoBrightnessValue: 100,
            resultFunction: function (res) 
                [].forEach.call(scannerLaser, function (el) 
                    fadeOut(el, 0.5);
                    setTimeout(function () 
                        fadeIn(el, 0.5);
                    , 300);
                );
                scannedImg.src = res.imgData;
                scannedQR[txt] = res.code;
                UserCheckId();
            
          ;
          function UserCheckId() 
              $.ajax(
                    contentType: 'application/json; charset=utf-8',
                    crossDomain: true,
                    type: "POST",
                    dataType: "json",
                    url: '@Url.Action("UserCheckId", "Home")',
                    data:  qrcode: JSON.stringify(scannedQR[txt]) ,
                    success: function (data) 
                        alert(data);
                    
                );
            
</script>
        [HttpPost]
        [AutoValidateAntiforgeryToken]
        public ActionResult UserCheckId(string qrcode)
        
            string result = qrcode;
            return Json(result, System.Web.Mvc.JsonRequestBehavior.AllowGet);
        

我更新了代码并显示了我在哪里调用函数“UserCheckId”。

【问题讨论】:

第一个示例代码是放在 JS 文件中还是放在 Razor 页面中? 我在 razor pages 中编写脚本 @Peter 将控制器从 URL HomeController 删除到 Home @Arib Yousuf 同样的错误“加载资源失败:服务器响应状态为 400 ()” 400 错误请求-data: qrcode : JSON.stringify(scannedQR[txt]) 【参考方案1】:

我找到了解决方案。 我在配置的 Startup.cs 中添加了以下行并且它起作用了。

            app.UseEndpoints(endpoints =>
            
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "controller=Home/action=Index/id?");
                endpoints.MapRazorPages();
            );

【讨论】:

以上是关于asp net core 5中的Ajax错误请求400的主要内容,如果未能解决你的问题,请参考以下文章

如何在 asp.net core 中使用 ajax 创建评论列表? [关闭]

Asp.net mvc 4 jquery ajax请求返回内部服务器错误

ASP.NET Core Razor中处理Ajax请求

ASP.net MVC Core Razor 页面和 Ajax JQuery

asp.net core webapi Post接收不到ajax请求数据

与 ASP.net MVC 中 Ajax 请求中的错误处理有关的疑问