Quantcast
Channel: Active questions tagged rest - Stack Overflow
Viewing all articles
Browse latest Browse all 3641

Sending file using RestSharp does Contain File

$
0
0

I want to upload a File using Post. When using Postman everything works fine and the file is uploaded as expected, but when I try the same with RestSharp my File is always empty.Am I doing something wrong?

According to the official Documentation, everything is correct.https://restsharp.dev/docs/next/usage/request#uploading-files

I found the following, Question on Stackoverflow, but it's a little bit outdatet and doesn't match work with the current Version of RestSharp.

RestSharp AddFile Using Stream

Test:

    [Fact]    public async Task Upload_ShouldWork()    {        //Arrange        await this._fixture.Login();        FileStream stream = File.OpenRead("C:\\Users\\Franz Seidl\\OneDrive\\Bilder\\testImage.png");        //Act        var result = await this._testClass.Upload(stream, 1, true);        //Assert        result.Should().BeTrue();    }

Client:

public async Task<bool> Upload(Stream fileStream, int id, bool force = false){        var request = new RestRequest($"{BaseUrl}Upload/{{id}}");        var fileParam = FileParameter.Create("upload",() => fileStream,"upload.png");        request.AddUrlSegment("id", id.ToString());        request.AddQueryParameter("force", force.ToString());        request.AddFile("upload.png", () => fileStream,"upload.png", ContentType.Binary);        var result = await this._client.PostAsync<bool>(request);        return result;}

Backend Code:

[HttpPost("Upload/{id}")]public async Task<ActionResult<bool>> UploadImage([FromRoute] int id, [FromQuery] bool force=false){    try    {        if (Request.ContentLength == 0 && Request.Body != null) throw new ArgumentException("No file provided");        var fileStream = Request.Body;        var result = await this._service.Upload(fileStream,id,force);        return result;    }    catch (ArgumentException e)    {        var errorDTO = this._exceptionHandler.HandleExceptionAndCreateDTO(e);        return this.BadRequest(errorDTO);    }    catch (Exception e)    {        var errorDTO = this._exceptionHandler.HandleExceptionAndCreateDTO(e);        return StatusCode(StatusCodes.Status500InternalServerError, errorDTO);    }}

I also tried sending the Request to a Postman MockServer, the result can be seen below.

Request against PostmanMockServer

Another interesting Detail when Sending the request per Postman, the Request.ContentLength is 1444 the same value as the FileStream.But when Sending with RestSharp the Request.Content is 1643.May be the file is not encoded correctly.


Viewing all articles
Browse latest Browse all 3641

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>