我一直在疯狂地研究,然后花了几个小时浏览我的代码,似乎找不到解决方案。我遍历了Stack Overflow,找不到与我的实现或特定问题相关的任何内容。
昨晚,我实现了一个Ajax Post函数,并且可以正常工作。然后,我开始修改(看似无关)的索引控制器操作,在此期间的某个时刻,Ajax Post停止工作,现在除了500错误外我什么也找不到。它只是应该将表单数据发送到控制器的Create操作。我会发布有关我的问题的更多信息,但是我不知道它的实际含义,因为500错误太模糊了。我一直在绞尽脑汁想弄清楚这一点,因此,我们将不胜感激!
Post.js
$('#createArea').hide();
$(document).on('click', "#createPostBtn", function () {
$('#createArea').show(300);
$('#createPostBtn').hide();
});
$(document).on('click', "#cancelPost", function () {
event.preventDefault();
$('#createArea').hide(300);
$('#createPostBtn').delay(300).show(100);
});
$(document).on("submit", "#createForm", function (event) {
// Prevents the default form behavior
event.preventDefault();
var $form = $(this);
$.ajax({
url: $form.attr("action"), // Get the action attribute from $form
type: $form.attr("method"), // Get the method attribute from $form
data: $form.serialize(), // Serialize $form
success: function (response) {
if (response === "Ok") {
$('#createArea').hide(300);
$('#createPostBtn').delay(300).show(100);
}
},
error: function () {
console.log("Could not create the post");
}
});
});
我不知道该问题可能与哪些文件有关,因为我的JS文件中没有重大更改可破解该文件,因此,我将在下面包括其他所有相关文件。
PostsController.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SparkPlug2.Models.Entities;
using SparkPlug2.Models.ViewModels;
using SparkPlug2.Services;
using System.Security.Principal;
using Microsoft.AspNetCore.Identity;
using SparkPlug2.Models;
namespace SparkPlug2.Controllers
{
[Authorize]
public class PostsController : Controller
{
private ISparkPlugRepository _repo;
UserManager<IdentityUser> _userManager;
public PostsController(ISparkPlugRepository repo, UserManager<IdentityUser> userManager)
{
_repo = repo;
_userManager = userManager;
}
public IActionResult Index()
{
var userID = _userManager.GetUserId(User);
// Filter by followed users
Collection<Post> followedPosts = new Collection<Post>();
foreach (Post post in _repo.ReadAllPosts())
{
if (_repo.IsFollowing(userID, post.AuthorId))
{
followedPosts.Add(post);
}
// Includes current user's posts in feed
if (post.AuthorId == userID)
{
followedPosts.Add(post);
}
}
var postList = followedPosts
.Select(p => new PostListVM
{
UserName = p.Author.UserName,
PostContent = p.Content,
PostedTime = p.PostedTime,
LikeCount = p.PostLike.Count
});
if(postList != null)
{
return View(postList);
}
// For debugging only
return RedirectToAction("Index", "Home");
}
private bool IsAjaxRequest()
{
return Request.Headers["X-Requested-With"] == "XMLHttpRequest";
}
[HttpPost, ValidateAntiForgeryToken]
public IActionResult Create(CreatePostVM postVM)
{
postVM.authorId = _userManager.GetUserId(User); // Pass current user's ID to VM as AuthorId
if (ModelState.IsValid)
{
// Use the repo to create the quote in the database
_repo.Create(postVM.CreatePost());
if (IsAjaxRequest())
{
return Json("Ok");
}
}
if (IsAjaxRequest())
{
return Json("Not Ok");
}
return RedirectToAction("Index", "Posts");
}
}
}
DbSparkPlugRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using SparkPlug2.Data;
using SparkPlug2.Models;
using SparkPlug2.Models.Entities;
namespace SparkPlug2.Services
{
public class DbSparkPlugRepository : ISparkPlugRepository
{
private readonly ApplicationDbContext _db;
private readonly sparkplugContext _spark;
private readonly UserManager<IdentityUser> _userManager;
public DbSparkPlugRepository(ApplicationDbContext db, sparkplugContext spark, UserManager<IdentityUser> userManager)
{
_db = db;
_spark = spark;
_userManager = userManager;
}
public IQueryable<IdentityRole> ReadAllRoles()
{
return _db.Roles;
}
public IQueryable<ApplicationUser> ReadAllUsers()
{
ICollection<ApplicationUser> appUsers = new List<ApplicationUser>();
foreach (var user in _db.Users)
{
ApplicationUser usr = new ApplicationUser
{
User = user
};
AddRoles(usr);
appUsers.Add(usr);
}
return appUsers.AsQueryable();
}
public IQueryable<Post> ReadAllPosts()
{
return _spark.Post
.Include(p => p.PostLike)
.Include(p => p.Author);
}
private void AddRoles(ApplicationUser user)
{
var roleIds = _db.UserRoles.Where(ur => ur.UserId == user.User.Id).Select(ur => ur.RoleId);
foreach (var roleId in roleIds)
{
user.Roles.Add(_db.Roles.Find(roleId));
}
}
// Hack to enable role-based authentication
public ApplicationUser ReadApplicationUser(string email)
{
ApplicationUser appUser = null;
var user = _db.Users.FirstOrDefault(u => u.Email == email);
if (user != null)
{
appUser = new ApplicationUser
{
User = user
};
AddRoles(appUser);
}
return appUser;
}
public bool AssignRole(string email, string roleName)
{
// Read the application user into user using email
var user = ReadApplicationUser(email);
// If user exists
if (user != null)
{
// If user does not have role roleName
if (!user.HasRole(roleName))
{
_userManager.AddToRoleAsync(user.User, roleName).Wait();
return true;
}
}
return false;
}
public bool IsFollowing(string userId, string followingId)
{
// FollowingUserId == current user (current user is following the followed user), testing if they follow 'followingId'
var result = _spark.Follow.Any(u => u.FollowingUserId == userId && u.FollowedUserId == followingId);
return result;
}
public Post Create(Post post)
{
_spark.Post.Add(post); //Add the post to the database's set of posts
_spark.SaveChanges(); //Commit changes to db
return post;
}
}
}