"请求实体的媒体类型' text / xml'此资源不支持。",

时间:2016-09-02 21:45:20

标签: c# json xml http asp.net-web-api2

我已成功使用C#程序对XML文档进行序列化和反序列化。我现在正在尝试接受在REST端点的HTTP请求正文中发布的XML文档。

但是,每次尝试时,都会收到以下错误消息:

"Message": "The request entity's media type 'text/xml' is not supported for this resource.",
"ExceptionMessage": "No MediaTypeFormatter is available to read an object of type 'XmlDocument' from content with media type 'text/xml'.",
"ExceptionType": "System.Net.Http.UnsupportedMediaTypeException",
 "StackTrace": "   at System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)\r\n   at System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)"

这是配置我正在使用的WebAPI的文件:

using System.Net.Http.Headers;
using System.Web.Http;
using FlexService.Formatters;
using Newtonsoft.Json.Serialization;

namespace FlexService
{
  public static class WebApiConfig
  {
      public static void Register(HttpConfiguration config)
      {
        // Use camel case for JSON data.
          config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new  CamelCasePropertyNamesContractResolver();
          config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
          config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml"));
          // Formatters are handled in appropriate order, so this must be inserted
          // before the JSON formatter that would return it as a .json object
          config.Formatters.Insert(0, new PngFormatter());

          // Web API routes
          config.MapHttpAttributeRoutes();

          config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional });
      }
  }
}

这是进行POST的控制器:

using System.Web.Http;
using Common.Models.Api;
using Core.Actions;
using FlexService.Attributes;
using Newtonsoft.Json.Linq;

namespace FlexService.Controllers
{
    [FlexRoutePrefix("orders")]
    public class OrderController : ApiController
    {
        [HttpGet, Route("{orderNumber}")]
        public ApiOrder GetInformation(string orderNumber)
        {
            return new OrderActions().GetOrderInformation(orderNumber);
        }

        [HttpPost, Route("new")]
        public System.Xml.XmlDocument Post([FromBody] System.Xml.XmlDocument     value)
        {
            return value;
        }
    }
}

简而言之,我尝试将文本作为XML进行POST,但由于某种原因,该程序正在接收它作为text / plain而不是text / xml。现在,我知道这个问题与我是否有

有关
     Content-Type: text/xml

在我的标题中,但我不知道如何解决这个问题。我假设这行代码

      config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/xml"));

会修复它,但它没有。有没有人有任何建议?

0 个答案:

没有答案