Adjust MVC 4 WebApi XmlSerializer to lose the nameSpace

前端 未结 4 1837
温柔的废话
温柔的废话 2020-12-05 15:28

I\'m working on a MVC WebAPI, that uses EF with POCO classes for storage. What I want to do is get rid of the namespace from the XML, so that the endpoints would return and

4条回答
  •  一个人的身影
    2020-12-05 16:29

    This answer here is spot on the mark Remove namespace in XML from ASP.NET Web API.\

    If you don't want to decorate your POCO's at all use the 1st option:

    config.Formatters.XmlFormatter.UseXmlSerializer = true;
    

    If you use option 2, you may need to add a reference to System.Runtime.Serialization

    Assuming a post like this with Accept set correct:

    GET http:// ANY OLD SERVER/api/foos/5 Accept: application/xml

    Controller

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Net;
    using System.Net.Http;
    using System.Runtime.Serialization;
    using System.Web.Http;
    
    namespace CutomXmlFormater.Controllers
    {
    //[DataContract(Namespace = "")]
    public class Foo
    {
        //[DataMember]
        public string Bar { get; set; }
    }
    
    public class FoosController : ApiController
    {
        // GET api/foos/5
        public Foo Get(int id)
        {
            return new Foo() { Bar = "Test" };
        }
    }
    

    }

    Config (App_Start/WebApiConfig)

    //(Use this is you don't go the data contact and model annotation route)
    config.Formatters.XmlFormatter.UseXmlSerializer = true;
    

    Result

    Either (With annotation and data contact):

    Test
    

    Or (with XML serialiser route):

    Test
    

提交回复
热议问题