从Web Api返回XML

时间:2018-07-18 00:46:11

标签: c# xml asp.net-web-api serialization

我已经阅读了数小时,并尝试了在SO上找到的许多不同解决方案,以及在其他地方但仍无法使它正常工作。

情况是,我编写了一个Web api rest服务,以通过COM提供与第三方应用程序的接口。它已经投产了几个月,并且可以完美运行。我一直受新用户的委托来提供XML响应,直到现在为止,它一直与JSON完美兼容。 无论我尝试什么,都无法使用Postman进行测试来获得XML响应。 在邮递员中,我将content-type和accept标头标记都设置为“ 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序列化方法并更改我的创建响应调用

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 除了例外,我不确定100%是否会产生正确格式的结果

更新 已经将我的业务类的属性更改为一个空的setter,现在在响应中获取带有属性的XML。 Visual Studio抱怨空的二传手,但是编译时,我猜这不是标准。

    public string Key
    {
        get { return _dataRecord.KeyField.ToString(); }
        set {} VS give me a wiggly green line on this but no info
    } 

1 个答案:

答案 0 :(得分:0)

对于所有帮助的人。万分感谢。 感谢Steve16351给我的提示使我朝正确的方向前进。

所以问题出在我定义DataObject类的方式上。我需要两个更改。

首先是一个无参数的构造函数。 其次,我需要指定属性设置器。最初我认为我不需要二传手,因为我不需要使用此类发布数据,因为其基础数据源是只读的。