Consider this client request:
var content = new MultipartFormDataContent();
var stream = new FileStream("c:\10GB.zip", FileMode.Open, FileAccess.Read);
content.Add(new StreamContent(stream), "file", fileInfo.Name);
request.Content = content;
var response = await httpClient.SendAsync(request);
if (response.IsSuccessStatusCode)
return Outcome<string>.Success($"{response.StatusCode} - {await response.Content.ReadAsStringAsync()}");
var result = await response.Content.ReadAsStringAsync();
return Outcome<string>.Fail($"Failed to upload file: {response.StatusCode} - {result}");
Now, in my API, I have middleware that looks for a valid token and rejects the request when token is missing or invalid for some reason:
context.Response.StatusCode = 401;
context.Response.ContentType = "application/json";
await context.Response.WriteAsync("{ \"error\": \"no token found\");
The middleware terminates the request by simply not invoking the next middleware. Is this behavior incorrect? What happens is the connection gets closed and the client throws a HttpRequestException
, and therefore never receives the formal 401 and response body (json).
Is there a more solid way to reject the request, when the request body is a large stream, that lets the client know his request got rejected? I have tested closing the stream but the connection gets terminated, resulting in a client-side exception anyway. Just sucking up the stream sounds like a pretty bad idea.