简体   繁体   中英

Is there a way to avoid http error 405 when uploading a file in asp net core web api?

I have an AJAX form which sends data (file uploads) to an ASP NET Web API using POST. I can hit my API end point without a problem and save the files and then return an OK. When the execution finishes on the API my page now display an error saying 405 method not allowed . I have configured CORS and allowed access to any origin also I have tried uploading the files using chrome with security disabled just to make sure its not CORS but still I am getting a Method not allowed when the code executes without a problem.

Below is my AJAX.

  <script>

    function uploadFiles() {    

        var fileUpload = $("#files").get(0);
        var files = fileUpload.files;
        var data = new FormData();

        for (var i = 0; i != files.length; i++) {
            data.append("files", files[i]);
        }
        $.ajax({
            type: "POST",

            url: "@TempData["api"]api/Document/BulkUpload/",
            headers: {
                'Authorization': 'Bearer @HttpContextAccessor.HttpContext.Session.GetString("token")'
            },

            contentType: false,
            processData: false,
            data: data,
            async: false,
            beforeSend: function () {
                //Before sending
            },
            success: function (messages) {
                var list = messages;
                $.each(list, function (index, item) {
                    //alertify.set('notifier', 'position', 'top-center');
                    //alertify.success('Successfully uploaded the Document');
                    alert(item);
                });

                let delay = 5000;
                let url = "/Documents";
                setTimeout(function () {

                    location = url;

                }, 5000);
            },
            error: function (e) {
                console.log(e.responseText);
                if (e.responseText == null) {
                    e.responseText = "Failed to upload Document. Contact the admin";
                }
                alertify.set('notifier', 'position', 'top-center');
                alertify.error(e.responseText);
            },
            complete: function () {
               //After sending
            }
        });

    }

</script>

Below is my API end point:

[HttpPost]
    [Route("BulkUpload")]
    public async Task<ActionResult> BulkUpload(IList<IFormFile> files)
    {
        //Errors
        List<string> Errors= new List<string>();

        var documents = files;

//Do whatever with the docs

}

Below are my CORS settings:

            app.UseCors(x => x
        .AllowAnyOrigin()
        .AllowAnyMethod()
        .AllowAnyHeader());

Below is my web.config file:

    <system.webServer>
    <httpProtocol>
        <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
            <add name="Access-Control-Allow-Methods" value="GET, PUT, POST, DELETE, OPTIONS" />
            <add name="Access-Control-Max-Age" value="1000" />
        </customHeaders>
    </httpProtocol>
</system.webServer>

Is there anything I am doing wrong?

After successful upload, you are setting the current location to the URL

/Documents

It seems like the corresponding endpoint does not support HTTP GET method allowed. Allowing the GET method allowed to that endpoint should resolve your issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM