Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to abort an HTTP post without reading its full contents (.NET REST service)

I have created a self-hosted .NET service that accepts binary uploads.

[ServiceContract]
public interface IBinaryService
{

    [OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "up/file/{fileName}/{hash}")]

    void FileUpload(string fileName, string hash, Stream fileStream);

When it receives a file, it first checks whether that file is already on the system, otherwise it streams the file from the client and saves it:

    public void FileUpload(string fileName, string hash, Stream fileStream)
    {
        string filebasedir = basedir + @"file\"; //" 
        if (File.Exists(filebasedir + hash))
        {

            WebOperationContext.Current.OutgoingResponse.StatusCode = 
                                   System.Net.HttpStatusCode.Conflict;
            return;
        }

        using(var fileToupload = new FileStream(
                string.Concat(filebasedir, hash),
                FileMode.Create))
                {
                fileStream.CopyTo(fileToupload);
                }

If I step through the code, I can see that the file content is not streamed until AFTER the server has read the parameters and decided whether there is a conflict. I just need to somehow force the server to not read the full contents (which could be many megabytes). Exiting the method early using 'return' does not do this unfortunately.

Is this possible?

like image 410
Jamona Mican Avatar asked Nov 14 '22 06:11

Jamona Mican


1 Answers

If I understand the issue you are facing correctly..

Client calls the method

void FileUpload(string fileName, string hash, Stream fileStream);

And as soon as it calls that function, it starts uploading the file to the server. You want to avoid or interrupt the file upload, if file already exists on the server.

Why don't you split your method in to two, one method will check if file already exists on the server (it will have only two arguments filename and hash, don't pass the filestream ), and return true or false, and if it doesn't exist then call the second method with filestream parameter.

That way it should solve your problem.

like image 138
Vishalgiri Avatar answered Nov 23 '22 23:11

Vishalgiri