How to cancel an upload

a 夏天 提交于 2019-12-22 09:25:27

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/26572954/how-to-cancel-an-upload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!