I'm building a React.js app with ASP.NET Core as backend following a tutorial course. I'm using Axios to handle HTTP requests, I tested the get, post, put requests working fine, but keep getting error during a del request. Here is the simplified function that produces the same error:
const handleDeleteActivityTest = () => {
Axios.delete('https://localhost:5001/api/activities/e2beb0eb-eaaa-49ee-92d8-daf472210456');
}
And the request prints the following error messages in the console:
DELETE https://localhost:5001/api/activities/e2beb0eb-eaaa-49ee-92d8-daf472210456 415 (Unsupported Media Type)
createError.js:16 Uncaught (in promise) Error: Request failed with status code 415 at createError (createError.js:16) at settle (settle.js:17) at XMLHttpRequest.handleLoad (xhr.js:61)
But I tested in Postman, and the delete request works just fine and returns a 200 OK response, and I can see in the database that the entry is deleted:
I would really appreciate if someone can educate me what's going on here. Thank you and stay safe & happy.
EDIT ----------------------------------
Here is the backend code that handles the HTTP request. It is divided into two parts-- 1.) controller that receives the HTTP request and 2.) MediatR class that handles it:
1.)
namespace API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ActivitiesController : ControllerBase
{
private readonly IMediator _mediator;
public ActivitiesController(IMediator mediator)
{
_mediator = mediator;
}
[HttpDelete("{id}")]
public async Task<ActionResult<Unit>> Delete(Guid id, Delete.Command command)
{
command.Id = id;
return await _mediator.Send(command);
}
}
}
2.)
namespace Application.Activities
{
public class Delete
{
public class Command : IRequest
{
public Guid Id { get; set; }
}
public class Handler : IRequestHandler<Command>
{
private readonly DataContext _context;
public Handler(DataContext context)
{
_context = context;
}
public async Task<Unit> Handle(Command request, CancellationToken cancellationToken)
{
var activity = await _context.Activities.FindAsync(request.Id);
if (activity == null)
throw new Exception("Could not find activity");
_context.Remove(activity);
var success = await _context.SaveChangesAsync() > 0;
if (success) return Unit.Value;
throw new Exception("Problem saving changes");
}
}
}
}
I found that the HttpDelete method in the controller receives id as a Guid, but in the React app id is typed as string, so I changed the type to string in the controller and MediatR class, but same http error 415.