繁体   English   中英

使用Ajax传递给ASP.NET Core Controller的参数始终为null

[英]Parameter passed to ASP.NET Core Controller using ajax is always null

我正在将mvc应用程序升级到.Net Core,并且难以通过ajax将字符串值传递给控制器​​。 我尝试了各种在Web上找到的解决方案( [FormBody] ,以= [FormBody] ,以及其他一些解决方案),但是没有运气。 该值始终为空。 我需要修复的Core发生了什么变化?

      var result = "";

  $.ajax({
      url: "https://......./api/lookups/Search",
      type: "POST",
      data: JSON.stringify(g),
      async: false,
      dataType: "json",
      contentType: 'application/json; charset=utf-8',
      success: function (data) {
       result = data;
    },
    done: function (data) {
       result = data;
    },
       fail: function (data) {
       result = data;
    },
       error: function (jqXHR, textStatus, errorThrown) {
       alert('request failed :' + errorThrown);
    }
});


using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using Microsoft.AspNetCore.Mvc;

namespace zpmAPI.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class LookupsController : ControllerBase
    {
        private zBestContext db = new zBestContext();

        // GET api/values
        [HttpGet]
        public string sayHello()
        {
            return "hello";
        }

        [HttpPost]
        //[Route("api/Lookups/LocationSearch")]
        public JsonResult LocationSearch(GeneralSearch g)
        {
            return new JsonResult( "hello from LocationSearch");
        }

您的控制器操作(我假设已配置为接受POST请求)

public string LoadChildrenAccounts(string parentID)

接受一个裸字符串作为参数,但是您要发布一个属性为string类型的对象( { "parentID": "12345" } )。

尝试将data: stringify({ "parentID": "12345" })更改为data: JSON.stringify("12345")

看来我一直在处理Cors问题,现在可以使用下面在Startup.cs和Controller中修改的代码来使其工作。

这样做的缺点是必须将“ Content-Type:'application / json'”添加到客户端的标头中才能起作用。 我不希望这样做,因为这将要求客户对其代码进行更新。 我读过的所有内容都表明,对Startup.cs文件的所示修改应允许我进行处理而无需修改post标头,但是Application似乎忽略了它。

using System.Collections.Generic;
using dbzBest.Models;
using Microsoft.AspNetCore.Mvc;

namespace zpmAPI.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Consumes("application/json")]
    public class PropertyController : ControllerBase
    {
        [HttpPost]
        public List<PropertyTile> Search(PropertySearch s)
        {
            try
            {
                List<PropertyTile> tiles = new List<PropertyTile>();
                dbzBest.Data.Properties db = new dbzBest.Data.Properties();
                tiles = db.Search(s);
                return tiles;
            }
            catch (System.Exception ex)
            {
                PropertyTile e = new PropertyTile();
                e.Description = ex.Message;
                List<PropertyTile> error = new List<PropertyTile>();
                error.Add(e);
                return error;
            }
        }
    }
}

在Startup.cs文件中

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {

                app.UseHsts();
            }

            /*add this line for CORS*/
            app.UseCors(opt => opt.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());
            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM