How to cancel a download
I have an app.net asp.net page where a user can upload some files. I am using jquery-file-upload . Based on some condition, I want to cancel the download from the server side, but it doesn't work. No matter what I do, the file always goes to the server before asp.net returns an error. For example, I can only save this on load:
public async Task<HttpResponseMessage> Post(int id, CancellationToken token)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, "Cant upload");
}
If I put a breakpoint on return
, I can see that it is removed as soon as the download starts, but I need to wait for the download to complete, and only then the javascript error handler is called. Is it possible to permanently complete the request by canceling the download?
Update 1:
I replaced jquery-file-upload with jquery-form and now I am using ajaxSubmit on my form. It didn't change anything. I also tried to implement DelegatingHandler
, for example:
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());
It didn't work either.
And I tried to disable the buffer on requests:
public class NoBufferPolicySelector : WebHostBufferPolicySelector
{
public override bool UseBufferedInputStream(object hostContext)
{
return false;
}
}
config.Services.Replace(typeof(IHostBufferPolicySelector), new NoBufferPolicySelector());
No play - it loads the whole file anyway before returning an error.
I only need to cancel the download request. Is this not possible with web api or am I missing something?
source to share
I had a similar problem and the only (admittedly ham-fisted) solution I could find to stop the client from downloading 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.
source to share