【问题标题】:Posting JSON object via AJAX to ASP.NET Core Web API通过 AJAX 将 JSON 对象发布到 ASP.NET Core Web API
【发布时间】:2020-12-03 07:28:29
【问题描述】:

我尝试了已在此站点上发布的不同方法,但似乎没有任何效果。 我想创建一个服装网站(个人项目)。网站上的产品有自己的类,是这样构建的:

 public class Product
 {
      public string ProductName { get; set; }
      public string ProductPrice { get; set; }

      public int Quantity { get; set; }
 }

购物车是另一个包含Product 对象列表的类,这个类是这样构建的:

public class ShoppingCart
{
    [Key]
    public int Id { get; set; }
    List<Product> ProductList { get; set; }

    public string ClientName { get; set; }

    public string ClientAddress { get; set; }

    public string ClientMail { get; set; }
}

我创建了一个 API 控制器类并认为可以解决问题。它看起来像这样:

[Route("api/Shopping")]
[ApiController]
public class ShoppingCartController : ControllerBase
{
    [HttpPost]
    public ShoppingCart Save([FromBody] ShoppingCart s)
    {
        return s;
    }
}

在我的 JavaScript 代码中,我创建了我的 JSON 对象并尝试像这样发布它:

 var orderB = document.getElementById("orderB");
    orderB.addEventListener("click", function () {
        var inputName = document.getElementById("inputName").value;
        var inputAddress = document.getElementById("inputAddress").value;
        var inputMail = document.getElementById("inputMail").value;
        var auxArray = [];

        for (var i = 0; i < productsAux.length; i++) {
            auxArray[i] = { "productName": productsAux[i].titlu, "productPrice": productsAux[i].pret, "quantity": localStorage.getItem(productsAux[i].titlu)};
        }

        var shoppingCart = {
            productList: auxArray,
            clientName: inputName,
            clientAddress: inputAddress,
            clientMail: inputMail
        };

        $.ajax({
            type: "POST",
            data: JSON.stringify(shoppingCart),
            url: "api/shopping/save",
            contentType: "application/json charset=utf-8",
             }).done(function (res) {
            alert(res);
        });
       

在我按下页面上的订单按钮后,我希望看到带有回调结果的警报弹出窗口,我认为这是使用我发送的 JSON 创建的 ShoppingCart 对象。

【问题讨论】:

  • 那么......什么不起作用?您是否检查了浏览器控制台以查看是否有任何错误?你检查过实际发布的内容吗?我们需要更多细节。
  • @Nikki9696 我的浏览器控制台没有任何错误。问题是我卡在这一步,我形成了我的 JSON 对象,现在我试图将它传递给我的控制器创建我的 C# 对象,然后将其添加到我的数据库中。在哪里可以看到发布的内容?
  • 在你的控制器方法中放置一个断点。
  • @ballonDor,在调试模式下运行你的 api(VS 中的 F5)并在左大括号处放置断点。顺便说一句,您不需要用[FromBody] 标记您的参数。如果操作方法接受复杂对象作为参数,WebAPI 使用注册的 MediaTypeFormatters 进行绑定。 WebAPI 中默认包含 json 内容类型的媒体类型格式化程序。
  • @ballonDor,现在删除 ajax 调用中的最后一个 url 段。网址应为 "api/shopping。默认情况下,WebApi 通过 HTTP 方法类型(GET、POST 等)指定调用方法,如果没有明确指定路由。

标签: javascript json asp.net-mvc api asp.net-core


【解决方案1】:

我打开“网络”选项卡,我得到了这个:我得到了 404(有点像 预计),方法的名称“保存”,类型“xhr”和 大小为 45B。

404 错误显然意味着 url/路由错误。这里要解决,有两种方法可以实现。

第一种方式:

您可以在 ajax 中将 url 更改为“api/shopping”,如下所示:

        $.ajax({
                type: "POST",
                data: JSON.stringify(shoppingCart),
                url: "api/shopping",
                contentType: "application/json charset=utf-8",
            }).done(function (res) {
                alert(res);
            })

第二种方式:

您可以更改路径名 Attribute routing with Http verb attributesSave 操作如下:

            [Route("api/Shopping")]
            [ApiController]
            public class ShoppingCartController : ControllerBase
            {
                [HttpPost("Save")]
                public ShoppingCart Save([FromBody] ShoppingCart s)
                {
            
                    return s;
                }
            }

更新

根据您的评论,除了以上更新外,您还需要修改routing设置如下:

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

调试结果:

【讨论】:

  • 这两种方法都试过了,好像都没有用。
  • @ballonDor,请向我们提供您的完整控制器代码,以及您的 starup.cs 文件中的 Configure 方法。
  • public void ConfigureServices(IServiceCollection services) { services.AddDbContext&lt;AppDbContext&gt;(option =&gt; option.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddControllersWithViews(); services.AddRazorPages().AddRazorRuntimeCompilation(); services.AddControllersWithViews().AddNewtonsoftJson(); services.AddControllersWithViews(options =&gt; { options.InputFormatters.Insert(0, GetJsonPatchInputFormatter()); }); }
  • 控制器代码与我之前发布的代码相同。我也像这样映射控制器:app.UseEndpoints(endpoints =&gt; { endpoints.MapControllers(); endpoints.MapRazorPages(); });
  • 设法解决了问题,一切正常。正如预期的那样,非常感谢您的帮助!!!非常感谢。
【解决方案2】:

对于稍后出现的人,我建议检查您的类型在两端是否正确。例如,如果您的 JS 正在发布一个字节数组,而 C# 尝试将其转换为 int,则整个对象(不仅仅是该道具)将为 null。

这让我很着迷。

【讨论】:

    猜你喜欢
    • 2016-11-06
    • 1970-01-01
    • 1970-01-01
    • 2015-10-02
    • 2023-03-17
    • 1970-01-01
    • 2011-06-14
    • 2018-02-28
    • 2017-01-16
    相关资源
    最近更新 更多