Search code examples
asp.net-coretinymce

How to upload images to server and restore them using Tinymce


I am trying to build a medium clone with asp.net core and TinyMCE. Tiny has an init property called image_upload_url. This property has '/WriteArticle' value and this page has an OnPost method that can answer post requests. But I am taking HTTP 400 bad requests when I am adding images to the editor. What should I do?

tiny initialize options:
automatic_uploads: true,
images_upload_url:'/WriteArticle',
images_upload_path:'/uploads',

WriteArticle.cshtml.cs method:

public IActionResult OnPost()
{
    Console.WriteLine("OnPost");
    try
    {
        var file = Request.Form.Files[0];
    var uploads = Path.Combine(_environment.WebRootPath, "uploads");
    var filePath = Path.Combine(uploads, file.FileName);

    using (var fileStream = new FileStream(filePath, FileMode.Create))
    {
        file.CopyTo(fileStream);
    }
    return new JsonResult(new { location = "/uploads/" + file.FileName });
    }
    catch (Exception ex)
    {
    return BadRequest(new { message = ex.Message });
    }
}

Solution

  • 400 (Bad Request) response because the framework expects the RequestVerificationToken as part of the posted request.The framework uses this to prevent possible CSRF attacks. If your request does not have this information, the framework will return the 400 bad request.

    Or you can bypass the checks by adding the IgnoreAntiforgeryTokenAttribute to the relevant PageModel class:

    [IgnoreAntiforgeryToken(Order = 1001)]
    public class IndexModel : PageModel
    {
        public void OnPost()
        {
        }
    }
    

    You can have a look at Request Verification to know more.