如何在MVC 4 Web Api中接收XmlDocument?

时间:2012-06-20 13:38:16

标签: asp.net-mvc api web xmldocument

我将XmlDocument发布到ApiController(从Windows服务,服务工作正常,它发布正确,我在wcf web api中使用它),但xml总是为null,我做错了什么? 我可以发布一些类,例如tutotials,或获取任何数据,一切都会好的,但我不能发布XmlDocument。

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

3 个答案:

答案 0 :(得分: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);
        }

答案 1 :(得分: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...}

答案 2 :(得分:0)

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

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

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