c# - 使用 js 发布到 api (asp.net core mvc)
问题描述
您好,我将 DTO 用于单个值(Id)并尝试使用 ApiController 发布到 Db,但是在单击按钮时,我不断收到错误 400,这将我引向 xhr.send 错误。(我使用 asp.net core 2.1)代码:@section Scripts{
<script type="text/javascript">
$(document)
.ready(function() {
$(".js-toggle-HandShake")
.click(function(e) {
var button = $(e.target);
console.log(button.attr("data-QuettaOfferId")); //Value=24 >> OK
$.post("/Api/HandShake/", { QuettaOfferId: button.attr("data-QuettaOfferId") })
// Error in > POST https://localhost:44339/Api/HandShake/ 400 () &
//in jquery>> xhr.send( options.hasContent && options.data || null );
.done(function() {
button
.text("Chousen");
})
.fail(function() {
alert("Something failed");
});
});
});
</script>
和 ApiController 代码
[Microsoft.AspNetCore.Mvc.Route("api/[controller]")]
[ApiController]
[Microsoft.AspNetCore.Authorization.Authorize]
public class HandShakeController : ControllerBase
{
private readonly ApplicationDbContext _context;
private readonly UserManager<IdentityUser> _userManager;
// private readonly IHostingEnvironment hostingEnvironment;
public HandShakeController(ApplicationDbContext context ,UserManager<IdentityUser> userManager/*, IHostingEnvironment environment*/)
{
_context = context;
_userManager = userManager;
//hostingEnvironment = environment;
}
[Microsoft.AspNetCore.Mvc.HttpPost]
// public IHttpActionResult HandShakes(HandShakeDto dto)
public IActionResult HandShakes(HandShakeDto dto)
{
var userId = _userManager.GetUserId(User);
var check = _context.Quetta.Where(u => u.SiteUserId == userId);
if ( _context.handShakes.Any(f => f.QuettaOfferId == dto.QuettaOfferId))
return BadRequest("Some error Msg");
if (check.Any())
{
var hand = new HandShake
{
QuettaOfferId = dto.QuettaOfferId
};
try
{
_context.handShakes.Add(hand);
_context.SaveChangesAsync();
return Ok();
}
catch (Exception e)
{
Console.WriteLine(e);
return BadRequest("Some error Msg");
}
}
else{
return BadRequest("");}
// Check if the user id that publish the ed = login user.
//if so add the offer to selected table,
}
}
我使用 asp.net core 2.1 & 强烈怀疑问题出在 ApiController 但我不确定。
DTO
public class HandShakeDto
{
public int QuettaOfferId { get; set; }
}
解决方案
$.post("/Api/Hand/", { QuettaOfferId: button.attr("data-QuettaOfferId") })
尝试
替换
$.post("/Api/HandShake/", { QuettaOfferId: button.attr("data-QuettaOfferId") })
因为您的 api 控制器名称是 HandShakeController
推荐阅读
- html - 外部样式表无效,但已链接
- python - Python:一步复制熊猫并替换特定列值
- firebase - 为什么部署firebase项目会给我一个路径错误?
- java - 为什么我的排序算法返回相同数量的比较?
- c++ - 我应该使用 Nuget 或 Vcpkg 安装适用于 C++ 的 AWS 开发工具包吗?
- javascript - 我怎样才能让我的倒计时计时器在我每次用 JavaScript 刷新时停止重新开始
- r - R list.files 未显示所有文件(可能是路径问题?)
- reactjs - 访问 reactjs 结构中的元素
- blockchain - 超级账本和 ICO 代币
- javascript - Twitter API - 发布收藏夹/创建特定速率限制