C# API Return string instead of XML wrapped string

后端 未结 3 811
栀梦
栀梦 2021-01-28 03:18

I\'m using ApiController and I can\'t get the call to return anything other than XML.

public class GuideController : ApiController
{
    [AcceptVerbs(\"GET\")]

         


        
相关标签:
3条回答
  • 2021-01-28 03:30

    An easy way to make sure the api only returns JSON is to remove the xml formatter from the http configuration.

    You can access the formatters in the WebApiConfig class

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API routes
            config.MapHttpAttributeRoutes();
    
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
    
            //Clear current formatters
            config.Formatters.Clear();
    
            //Add only a json formatter
            config.Formatters.Add(new JsonMediaTypeFormatter());
    
        }
    }
    

    UPDATE

    Don't serialize the object in the controller. Just return the object as is. Web api will do that for you as you have attached the json formatter to the configuration.

    public class GuideController : ApiController
    {
        [AcceptVerbs("GET")]
    
        [HttpGet]
        public IHttpActionResult Get()
        {
            Item item = Item.GetTestData();
            return Ok(item);
        }
    }
    
    0 讨论(0)
  • 2021-01-28 03:32

    Try setting the Accept header in the client. If you want to receive JSON, set

    Accept: application/json

    in your client. Hope that helps.

    0 讨论(0)
  • 2021-01-28 03:48

    Try to return JSON explicitly.

    [HttpGet]
    public IHttpActionResult Get()
    {
        Item item = Item.GetTestData();       
        return Json(item);
    }
    
    0 讨论(0)
提交回复
热议问题