Search code examples
asp.net-corefile-uploadantiforgerytoken

ASP.NET Core file uplloading through streaming with anti forgery token


I'm using the MultipartReader to upload a file through streaming and I was wondering if there's a way to validate the antiforgery token through code. If I add the ValidateAntiForgeryTokenAttribute to the method, then it will consume the form's body and I'll get an error:

Unexpected End Of Stream Exception

I could use JS on the client side to intercept the form's submit event, but this is a plain MVC form which also uses the MVC validation framework (and I'm thinking that intercepting the form's submit event to pass the token in the header will not play nicely with the validation's form submit interception).

Any ideas on how to solve this?

Thanks.


Solution

  • I've followed this sample and updated the client script so that it checks if the form is valid before performing the submit. Overall, it was easier than expected:

    $("#docForm").on("submit",
          (e) => {
            const frm = $(e.target);
            if (!frm.valid()) {
              return false;
            }
     // more code
     }