2

我将 XmlDocument 发布到 ApiController (来自 Windows 服务,服务工作正常,发布正确,我在 wcf web api 中使用它),但 xml 始终为空,我做错了什么?我可以发布一些课程,例如教程,或者获取任何数据,一切都会好起来的,但我不能发布 XmlDocument。

public class XmlController : ApiController
{
    public void PostXml(XmlDocument xml)
    {
       // code
    }
}
4

3 回答 3

2

我遵循@Rhot给出的解决方案,但不知何故它不起作用,所以我编辑如下对我有用的:

public class XmlMediaTypeFormatter : MediaTypeFormatter
    {
        public XmlMediaTypeFormatter()
        {
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xml"));
        }

        public override bool CanReadType(Type type)
        {
            return type == typeof(XDocument);
        }

        public override bool CanWriteType(Type type)
        {
            return type == typeof(XDocument);
        }

        public override Task<object> ReadFromStreamAsync(Type type, Stream stream, HttpContent content, IFormatterLogger formatterLogger)
        {
            var reader = new StreamReader(stream);
            string value = reader.ReadToEnd();            

            var tcs = new TaskCompletionSource<object>();
            try
            {
                var xmlDoc = XDocument.Parse(value);
                tcs.SetResult(xmlDoc);
            }
            catch (Exception ex)
            {
                //disable the exception and create custome error
                //tcs.SetException(ex);
                var xml = new XDocument(
                    new XElement("Error",
                        new XElement("Message", "An error has occurred."),
                        new XElement("ExceptionMessage", ex.Message)
                ));

                tcs.SetResult(xml);
            }

            return tcs.Task;
        }

        public override Task WriteToStreamAsync(Type type, object value, Stream stream, HttpContent content, TransportContext transportContext)
        {
            var writer = new StreamWriter(stream);
            writer.Write(((XDocument)value).ToString());
            writer.Flush();

            var tcs = new TaskCompletionSource<object>();
            tcs.SetResult(null);
            return tcs.Task;
        }              
    }

注册到 global.asax:

GlobalConfiguration.Configuration.Formatters.Insert(0, new XmlMediaTypeFormatter());

在我的 WebAPI 控制器下方:

public HttpResponseMessage Post(XDocument xml)
        {            
            return Request.CreateResponse(HttpStatusCode.OK, xml);
        }
于 2012-12-05T15:11:02.497 回答
1

我找到了一个解决方案:

我们需要使用继承来继承MediaTypeFormatter

public class XmlMediaTypeFormatter : MediaTypeFormatter
{
    public XmlMediaTypeFormatter()
    {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml"));      
    }

    public override System.Threading.Tasks.Task<object> ReadFromStreamAsync(Type type, Stream stream,
         HttpContentHeaders contentHeaders,
         IFormatterLogger formatterLogger)
    {
        var taskCompletionSource = new TaskCompletionSource<object>();
        try
        {
            var memoryStream = new MemoryStream();
            stream.CopyTo(memoryStream);
            var s = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(s);

            taskCompletionSource.SetResult(xmlDoc);
        }
        catch (Exception e)
        {
            taskCompletionSource.SetException(e);
        }
        return taskCompletionSource.Task;
    }

    public override bool CanReadType(Type type)
    {
        return type == typeof(XmlDocument);
    }

    public override bool CanWriteType(Type type)
    {
        return false;
    }
}

然后在 Global.asax 中注册:

GlobalConfiguration.Configuration.Formatters.Insert(0, new XmlMediaTypeFormatter());

控制器:

public HttpResponseMessage PostXml([FromBody] XmlDocument xml)
    {//code...}
于 2012-06-26T12:48:28.677 回答
0

PostXml应该是控制器上的动作吗?如果是这样,您应该将控制器操作标记为接受 HttpPost。从那里我将修改操作,如下所示:

[HttpPost]
public ActionResult PostXml(HttpPostedFileBase xml)
{
    // code
}

如果您仍然无法接受发布的文件,请启动调试器并检查请求文件集合:http: //msdn.microsoft.com/en-us/library/system.web.httprequest.files.aspx

于 2012-06-21T17:04:42.113 回答