我正在将mvc应用程序升级到.Net Core,并且难以通过ajax将字符串值传递给控制器。我尝试了各种在Web上找到的解决方案([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");
}
答案 0 :(得分:-1)
您的控制器操作(我假设已将其配置为接受POST请求)
public string LoadChildrenAccounts(string parentID)
接受裸露的字符串作为参数,但是您要发布具有字符串类型({ "parentID": "12345" }
)属性的对象。
尝试将data: stringify({ "parentID": "12345" })
更改为data: JSON.stringify("12345")
答案 1 :(得分:-1)
看来我一直在处理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();
}
}
}