Attempting to post XML file to MVC RESTful API and

2019-07-28 20:32发布

问题:

The front end seems to post fine and my routing seems to be working as my API seems to get the request and the filename is valid. However, when I attempt await request.Content.ReadAsStreamAsync(); it doesn't seem to read anything and I get a

Data at the root level is invalid. Line 1, position 1.

exception when de-serializing...

Been at this for awhile trying the different solutions available with no success.. please help.

Things I've tried:

  • Different content-types
  • Different webclient methods to upload (uploadstring, uploadfile, uploaddata)
  • Using WebRequest instead of webclient (I will consistently get an unsupported media type message as a response)

My code:

public string CreateJob()
    {
        string test = "";
        string sURL = "http://" + _domain + _apiRoot + "CreateJob/OrderXML";


        try
        {
            var ms = new MemoryStream();

            using (FileStream src = System.IO.File.Open(@"C:\XML\PageDNAOrderXML.txt", FileMode.Open))
            {
                src.CopyTo(ms);
            }

            using (WebClient wc = new WebClient())
            {
                wc.Headers[HttpRequestHeader.ContentType] = "text/xml";
                wc.Headers[HttpRequestHeader.AcceptEncoding] = "Encoding.UTF8";
                //wc.Headers[HttpRequestHeader.ContentLength] = ms.Length.ToString();                    
                wc.UploadString(sURL, ms.ToString());
            }
        }
        catch (Exception ex)
        {
            test = ex.Message;

        }
        return test;
    }     

RESTful API

 [System.Web.Http.HttpPost]
    public async void CreateJob(string filename)
    {
        string success = "false";
        try
        {
            //XDocument doc = XDocument.Load
            XmlSerializer xmls = new XmlSerializer(typeof(PdnaXmlParse));
            Stream reqStream = await Request.Content.ReadAsStreamAsync();
            PdnaXmlParse res = (PdnaXmlParse)xmls.Deserialize(new XmlTextReader(reqStream));
        }
        catch (Exception ex)
        {
            Console.Write(ex.Message);
        }
}