0

i tried to send a basic file from my integration test project in C# to a web api . But i don't know why, each call i get an exception .

Json.JsonSerializationException : Error getting value from 'ReadTimeout' on 'System.Io.FileStream'

I found this property can't be read , so maybe that why my httpclient can't serialize it. So how can i send a file to a web api ?

This is my code from the client:

using (StreamReader reader = File.OpenText("SaveMe.xml"))
{
    response = await client.PostAsJsonAsync($"api/registration/test/", reader.BaseStream);
    response.EnsureSuccessStatusCode();
}

And my controller:

[Route("api/registration")]
public class RegistrationController : Controller
{
    [HttpPost, Route("test/")]
        public ActionResult AddDoc(Stream uploadedFile)
        {
            if (uploadedFile != null)
            {
                return this.Ok();
            }
            else
            {
                return this.NotFound();
            }

        }

Here the screenShot we can see , the property [ReadTimeout] can't be access. enter image description here

Mehdi Bugnard
  • 3,889
  • 4
  • 45
  • 86

2 Answers2

3

I'm not sure if they still support PostAsJsonAsync in .NET Core, which I am on. So I decided to rewrite your snippet as follows using PostAsync:

    using (StreamReader reader = File.OpenText("SaveMe.xml"))
    {
    var response = await client.PostAsync($"api/registration/test/", new StreamContent(reader.BaseStream));                                   
    }

Update your API method to look like:

[Route("api/registration")]
public class RegistrationController : Controller
{
    [HttpPost, Route("test/")]
    public ActionResult AddDoc()
    {
        //Get the stream from body
        var stream = Request.Body;
        //Do something with stream
    }
Felix Too
  • 11,614
  • 5
  • 24
  • 25
0

First you have to read all the data from file and only then send it. To open the .xml files use XmlReader. look here Reading Xml with XmlReader in C#

Anton
  • 1