Asp.Net Ajax 500 Ошибка - перестала работать функция Post - PullRequest
0 голосов
/ 12 декабря 2018

Я занимаюсь исследованиями как сумасшедший, и часами просматриваю свой код и, похоже, не могу найти решение.Я просмотрел переполнение стека и не могу найти ничего, имеющего отношение к моей реализации или конкретной проблеме.

Прошлой ночью я реализовал функцию 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;
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...