代码之家  ›  专栏  ›  技术社区  ›  Hursey

从Web API返回XML

  •  2
  • Hursey  · 技术社区  · 8 年前

    我已经阅读了几个小时,尝试了许多不同的解决方案,我已经找到了,在其他地方,仍然无法得到这个工作。

    情况是,我编写了一个Web API REST服务,通过COM向第三方应用程序提供接口。它已经投入生产几个月了,而且工作完美无瑕。我的任务是由一个新的消费者提供XML响应,到目前为止,它只与JSON一起工作,非常好。 无论我做什么尝试,我都无法使用postman获得XML响应进行测试。 在PostMan中,我将Content-Type和Accept-Header标记都设置为“application/xml”。

    所以我的控制器很简单

    public class SampleController : ApiController
    {
        [HttpGet]
        [Route("api/getobject")]
        public HttpResponseMessage GetByGSTNumber(string token, string key)
        {
            DataConnection connection = null; new DataConnection();//Set up COM reference
            DataObject dataObj = null;
            try
            {
                connection = new DataConnection();
                connection.login(token);
                dataObj = new DataObject(connection);
                Request.CreateResponse(HttpStatusCode.OK, dataObj);
            }
            catch (Exception ex)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex);
            }
            finally
            {
                if (connection != null) { Request.RegisterForDispose(connection); }
                if (dataObj != null) { Request.RegisterForDispose(dataObj); }
            }
        }
    }
    

    我的数据对象的定义,同样不要认为过于复杂。它在引擎盖下做了一些解析,将非clr类型转换为clr类型。

    public class DataObject : IDisposable
    {
        internal DataConnection dbConnection;
        internal dynamic _dataRecord;
        public string Key
        {
            get { return _dataRecord.KeyField.ToString(); }
        }
    
        public string Property1
        {
            get { return _dataRecord.Property1Feild.ToString(); }
        }
    
        public DataObject(DataConnection connection)
        {
            dbConnection = connection;
        }
    
        public void OpenRecord(string key)
        {
            if (!_dataRecord.Seek(key))
            {
                throw new Exception("Record not found");
            }
    
        }
    
        #region IDisposable Support
    }
    

    所以到目前为止我尝试的是改变

    return Request.CreateResponse(HttpStatusCode.OK, dataObj);
    //Returns JSON even if specifying XML in request
    

    到

    return Request.CreateResponse(HttpStatusCode.OK, dataObj "application/xml");
    // returns <ExceptionMessage>Could not find a formatter matching the media type 'application/xml' that can write an instance of 'DataObject'.</ExceptionMessage>
    

    我已经用[datacontract]修饰了我的数据对象,用[datamember]标记修饰了属性,但这并没有导致任何更改。

    我已经创建了一个无参数的构造函数,这让我明白了,但是XML中没有属性/值。

    我已经尝试在global.asax文件中设置XML序列化程序,但这没有明显的效果。 我错过了什么?

    更新 包含的应用程序启动,在这里我尝试了不同的useXmlSerializer=true/false组合,并进行了上述所有更改

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
    
            var xml = GlobalConfiguration.Configuration.Formatters.XmlFormatter;
            xml.UseXmlSerializer = true;
        }
    

    我还尝试在我的数据对象上放置一个XML序列化方法,并更改我的create-response调用。

    public string XMLSerialize()
        {
            XmlSerializer xsSubmit = new XmlSerializer(typeof(DataObject));
            using (var sww = new StringWriter())
            {
                using (XmlWriter writer = XmlWriter.Create(sww))
                {
                    xsSubmit.Serialize(writer, this);
                    return sww.ToString(); // Your XML
                }
            }
        }
    

    return request.createResponse(httpstatuscode.ok,creditor.xmlserialize(),“application/xml”);

    这会导致 生成XML文档时出错。 System.InvalidOperationException 除了例外,我不能百分之百地肯定这会产生一个正确格式化的结果。

    更新 已将我的业务类的属性更改为具有空的setter,现在正在获取响应中包含属性的XML。Visual Studio抱怨空的setter,但是编译,我猜这不是标准。

        public string Key
        {
            get { return _dataRecord.KeyField.ToString(); }
            set {} VS give me a wiggly green line on this but no info
        } 
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   Hursey    8 年前