Leo
Leo

Reputation: 7449

How to cancel an upload

I have a asp.net web api page where the user can upload some files. I am using jquery-file-upload. Based on some condition, I want to cancel the upload from the server side but it is not working. No matter what I do, the file always goes to the server before asp.net returns the error. Example, I can keep just this when uploading:

public async Task<HttpResponseMessage> Post(int id, CancellationToken token)
{
    return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Cant upload");
}

If I put a breakpoint on the return, I can see that it is hitted as soon as the upload starts but I have to wait the upload to end and only then the javascript error handler gets called. Is it not possible to end the request imediatelly, cancelling the upload?

Update 1:

I replaced jquery-file-upload with jquery-form and now I am using ajaxSubmit on my form. This doen't changed anything. I also tried to implement a DelegatingHandler, like this:

public class TestErrorHandler : DelegatingHandler
{
    protected async override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {

        //throw new HttpException(403, "You can't upload");

        var response = request.CreateResponse(HttpStatusCode.Unauthorized);
        response.ReasonPhrase = "You can't upload";
        return Task.FromResult<HttpResponseMessage>(response).Result;            
    }
}

config.MessageHandlers.Add(new TestErrorHandler());

That did not work either.

And I tried to disable buffer on requests:

public class NoBufferPolicySelector : WebHostBufferPolicySelector
{
    public override bool UseBufferedInputStream(object hostContext)
    {
        return false;   
    }        
}

config.Services.Replace(typeof(IHostBufferPolicySelector), new NoBufferPolicySelector());

No game - it still upload all the file before returning the error.

All I need is to cancel a upload request. Is this impossible with web api or I am missing something here?

Upvotes: 3

Views: 1320

Answers (1)

Christoph Albert
Christoph Albert

Reputation: 41

I had a similar problem, and the only (admittedly ham-fisted) solution I could find to stop the client from uploading the data was to close the TCP connection:

var ctx = Request.Properties["MS_HttpContext"] as HttpContextBase;
if (ctx != null) ctx.Request.Abort();

This works for IIS hosting.

Upvotes: 1

Related Questions