Quantcast
Channel: Active questions tagged blazor - Stack Overflow
Viewing all articles
Browse latest Browse all 4839

405 Method Not Allowed when Posting Comments and Ratings in ASP.NET Core API

$
0
0

I have a problem where I have a user click on a link "/movie-details.html?id=@movie.Id". The user is showed a option to make a comment and rate the movie. But when Sending the information, I keep getting the

movie-details.js:69POST https://localhost:7007/api/comments 405 (Method Not Allowed)movie-details.js:85 Error: SyntaxError: Failed to execute 'json' on 'Response': Unexpected end of JSON inputat movie-details.js:79:36 

same with rating.

Here is my code:

  public class CommentDto  {      public string Text { get; set; }      public DateTime CreatedDate { get; set; }      public string UserName { get; set; }      public int MovieId { get; set; }  }  public class CommentCreateDto  {      public int MovieId { get; set; }      public string Text { get; set; }  }  public class RatingDto  {      public int Value { get; set; }      public DateTime CreatedDate { get; set; }      public string UserName { get; set; }  }  public class RatingCreateDto  {      public int MovieId { get; set; }      public int Value { get; set; }  }

movie-details.js

async function submitComment() {    const commentText = document.getElementById('commentText').value;    try {        const response = await fetch('/api/comments', {            method: 'POST',            headers: {'Content-Type': 'application/json'            },            body: JSON.stringify({                movieId: currentMovieId,                text: commentText            })        });        const data = await response.json();        if (!response.ok) {            throw new Error(data.error || "Neznámá chyba");        }        alert("Komentář uložen: " + data.message);        loadComments();    } catch (error) {        console.error("Chyba:", error);        alert("Chyba: " + error.message);    }}function submitRating() {    const ratingValue = document.getElementById('ratingValue').value;    fetch('/api/ratings', {        method: 'POST',        headers: {'Content-Type': 'application/json'        },        body: JSON.stringify({            movieId: parseInt(new URLSearchParams(window.location.search).get('id')),            value: ratingValue        })    })        .then(response => response.json())        .then(data => {            if (data.success) {                loadRatings();            }        })        .catch(error => console.error('Error:', error));}

And the CommentController.cs:

 [ApiController] [Route("api/[controller]")] public class CommentsController : ControllerBase {     private readonly ApplicationDbContext _context;     public CommentsController(ApplicationDbContext context)     {         _context = context;     }     [HttpGet]     public async Task<ActionResult<IEnumerable<CommentDto>>> GetComments(int movieId)     {         return await _context.Comments             .Where(c => c.MovieId == movieId)             .Include(c => c.User)             .Select(c => new CommentDto             {                 Text = c.Text,                 CreatedDate = c.CreatedDate,                 UserName = c.User.UserName             })             .ToListAsync();     }     [HttpPost]     public async Task<IActionResult> AddComment([FromBody] CommentCreateDto comment)     {         if (comment == null)         {             return BadRequest("Invalid comment data.");         }         await _context.Comments.AddAsync(new Comment         {             Text = comment.Text,             UserId = comment.UserName,             MovieId = comment.MovieId,             CreatedDate = DateTime.UtcNow         });         await _context.SaveChangesAsync();         return Ok("Comment added successfully.");     } }

(Similar with rating)

I've tried Disabling authorization, didn't help. I want it to asign the comment and rating to the logged user and send it to the database.


Viewing all articles
Browse latest Browse all 4839

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>