XML解析错误:在ASP.NET Core 2.0 API中找不到根元素
我遇到了这个问题,但无法解决.我正在使用ASP.NET Core 2和Ajax.
I've encountered this problem, and I couldn't figure it out. I'm using ASP.NET Core 2 and Ajax.
这是JavaScript调试器所说的:
This is what the JavaScript debugger says:
XML解析错误:找不到根元素位置: http://localhost:52617/api/favorites/第1行,第1列:>
XML Parsing Error: no root element found Location: http://localhost:52617/api/favorites/ Line Number 1, Column 1:
这是我的JavaScript代码:
This is my JavaScript code:
$(".js-toggle-fav").click(function (e) {
function sendPost() {
console.log("inside post send");
var button = $(e.target);
$.ajax({
type: 'POST',
url: "http://localhost:52617/api/Favorites/",
data: {"EventId": @Model.Event.EventId},
contentType: "application/json; charset=utf-8"
});
}
$.getJSON("http://localhost:52617/api/favorites/@Model.Event.EventId", function (data) {
if (data == null) {
console.log("fav is null");
sendPost();
fav.addClass(toggling);
fav.text("unfav");
}
else {
console.log("fav is NOT null");
sendPost();
fav.removeClass(toggling);
fav.text("fav");
}
);
});
还有我的API:
[HttpPost]
public async Task<IActionResult> PostFavorite([FromBody] FavoriteDto favorite)
{
if (!ModelState.IsValid)
{
Console.WriteLine(ModelState.ValidationState.ToString());
return BadRequest(ModelState);
}
var uid = _userManager.GetUserId(HttpContext.User);
var fav = await _context.Favourites.SingleOrDefaultAsync(x => x.EventId == favorite.EventId && x.UserId == uid);
if (fav == null)
{
_context.Favourites.Add(new Favorite { EventId = favorite.EventId, UserId=uid });
}
else
{
_context.Favourites.Remove(fav);
}
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateException)
{
if (FavoriteExists(favorite.EventId))
{
return new StatusCodeResult(StatusCodes.Status409Conflict);
}
else
{
throw;
}
}
return Ok(favorite);
}
当我与Postman或任何restclient一起执行此操作时,所有内容都像魅力一样!使用Ajax并非如此.
When I do this with Postman or any restclient, everything works like a charm! With Ajax, that's not the case.
注意:
- 在同一个
.cshtml
文件中,还有更多的jQuery和JavaScript代码可以执行类似的操作,并且可以正常工作!所有解决方案不幸的是,我已经检查过互联网无法正常工作. - Get方法(用于返回List或单个元素正在工作!)
- In the same
.cshtml
file, there's more jQuery and JavaScript code which does something like this, and it's just working! All the solutions I've checked on the internet didn't work, unfortunately. - The Get methods (for returning List, or single element are working!)
问题来自
data: {"EventId": @Model.Event.EventId},
使用JSON.Stringify
Instead of passing it in directly, use JSON.Stringify
var payload = {EventId: @Model.Event.EventId};
$.ajax({
type: 'POST',
url: "http://localhost:52617/api/Favorites/",
data: JSON.stringify(payload),
contentType: "application/json; charset=utf-8"
});
我假设您的FavoriteDto类看起来像这样
I'm assuming your FavoriteDto class looks something like this
public class FavoriteDto
{
public int EventId { get; set; }
}
出现xml错误的原因是控制器动作
The reason why you were getting an xml error is that the controller action
public async Task<IActionResult> PostFavorite([FromBody] FavoriteDto favorite)
无法解析收藏夹",因此它从未初始化且为空.然后,您返回ok(null),当它从服务器接收回响应时,这会在客户端ajax上导致解析错误.
could not parse 'favorite' so it was never initialised and was null. You then return ok(null) which caused a parsing error on your client side ajax when it recieved the response back from your server.