How to return Json data from MVC Controller in C#









up vote
1
down vote

favorite
1












I am using a Repository pattern with Entity Framework, When i run my code instead of Json Data I am getting -> System.Collections.Generic.List`1[MovieInfo.Core.Models.Models.User]



Repository



public interface IRepository<T> where T : class

IEnumerable<T> Get();

T GetDetails(Guid Id);

void Insert(T data);

void Delete(T data);

void Update(T data);

void Save();


public GenericRepository()

context = new Entities();
dbEntity = context.Set<T>();



Services



public class TestService : ITestService

public TestService(
IRepository<User> userRepository
)

_userRepository = userRepository;


private readonly IRepository<User> _userRepository;

public IEnumerable<User> Get()


var result = _userRepository.Get();

return result;




Controller



public class HomeController : Controller

public HomeController(ITestService testService)

_testService = testService;


private readonly ITestService _testService;

public IEnumerable<User> Index()

var result = _testService.Get();

return result;




I found some solution on here (StackOverflow) that I need to add WebApiConfig, I added as below but it also not work. I am getting the output
System.Collections.Generic.List`1[MovieInfo.Core.Models.Models.User]



 public static class WebAppConfig

public static void Register(HttpConfiguration config)

config.Formatters.Remove(new XmlMediaTypeFormatter());

config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data"));

config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/controller/action/id",
defaults: new

id = RouteParameter.Optional

);




Here is my Git Repository Link
https://github.com/Harshk16/MovieInfo



Please help me out how to get output in Json Format










share|improve this question





















  • Where and when are you getting that output ? What is your expected behavior ?
    – Shyju
    Nov 10 at 17:32










  • Instead of inheriting your Home controller with System.Web.Mvc.Controller, you must inherit it with System.Web.Http.ApiController
    – Kundan Singh Chouhan
    Nov 10 at 17:32










  • @Shyju I want last output result as json System.Collections.Generic.List`1[MovieInfo.Core.Models.Models.User] is my output result I also added my git repo link
    – Harsh
    Nov 10 at 17:46











  • @KundanSinghChouhan can you please give me some example,I also added my git repo link above
    – Harsh
    Nov 10 at 17:48














up vote
1
down vote

favorite
1












I am using a Repository pattern with Entity Framework, When i run my code instead of Json Data I am getting -> System.Collections.Generic.List`1[MovieInfo.Core.Models.Models.User]



Repository



public interface IRepository<T> where T : class

IEnumerable<T> Get();

T GetDetails(Guid Id);

void Insert(T data);

void Delete(T data);

void Update(T data);

void Save();


public GenericRepository()

context = new Entities();
dbEntity = context.Set<T>();



Services



public class TestService : ITestService

public TestService(
IRepository<User> userRepository
)

_userRepository = userRepository;


private readonly IRepository<User> _userRepository;

public IEnumerable<User> Get()


var result = _userRepository.Get();

return result;




Controller



public class HomeController : Controller

public HomeController(ITestService testService)

_testService = testService;


private readonly ITestService _testService;

public IEnumerable<User> Index()

var result = _testService.Get();

return result;




I found some solution on here (StackOverflow) that I need to add WebApiConfig, I added as below but it also not work. I am getting the output
System.Collections.Generic.List`1[MovieInfo.Core.Models.Models.User]



 public static class WebAppConfig

public static void Register(HttpConfiguration config)

config.Formatters.Remove(new XmlMediaTypeFormatter());

config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data"));

config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/controller/action/id",
defaults: new

id = RouteParameter.Optional

);




Here is my Git Repository Link
https://github.com/Harshk16/MovieInfo



Please help me out how to get output in Json Format










share|improve this question





















  • Where and when are you getting that output ? What is your expected behavior ?
    – Shyju
    Nov 10 at 17:32










  • Instead of inheriting your Home controller with System.Web.Mvc.Controller, you must inherit it with System.Web.Http.ApiController
    – Kundan Singh Chouhan
    Nov 10 at 17:32










  • @Shyju I want last output result as json System.Collections.Generic.List`1[MovieInfo.Core.Models.Models.User] is my output result I also added my git repo link
    – Harsh
    Nov 10 at 17:46











  • @KundanSinghChouhan can you please give me some example,I also added my git repo link above
    – Harsh
    Nov 10 at 17:48












up vote
1
down vote

favorite
1









up vote
1
down vote

favorite
1






1





I am using a Repository pattern with Entity Framework, When i run my code instead of Json Data I am getting -> System.Collections.Generic.List`1[MovieInfo.Core.Models.Models.User]



Repository



public interface IRepository<T> where T : class

IEnumerable<T> Get();

T GetDetails(Guid Id);

void Insert(T data);

void Delete(T data);

void Update(T data);

void Save();


public GenericRepository()

context = new Entities();
dbEntity = context.Set<T>();



Services



public class TestService : ITestService

public TestService(
IRepository<User> userRepository
)

_userRepository = userRepository;


private readonly IRepository<User> _userRepository;

public IEnumerable<User> Get()


var result = _userRepository.Get();

return result;




Controller



public class HomeController : Controller

public HomeController(ITestService testService)

_testService = testService;


private readonly ITestService _testService;

public IEnumerable<User> Index()

var result = _testService.Get();

return result;




I found some solution on here (StackOverflow) that I need to add WebApiConfig, I added as below but it also not work. I am getting the output
System.Collections.Generic.List`1[MovieInfo.Core.Models.Models.User]



 public static class WebAppConfig

public static void Register(HttpConfiguration config)

config.Formatters.Remove(new XmlMediaTypeFormatter());

config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data"));

config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/controller/action/id",
defaults: new

id = RouteParameter.Optional

);




Here is my Git Repository Link
https://github.com/Harshk16/MovieInfo



Please help me out how to get output in Json Format










share|improve this question













I am using a Repository pattern with Entity Framework, When i run my code instead of Json Data I am getting -> System.Collections.Generic.List`1[MovieInfo.Core.Models.Models.User]



Repository



public interface IRepository<T> where T : class

IEnumerable<T> Get();

T GetDetails(Guid Id);

void Insert(T data);

void Delete(T data);

void Update(T data);

void Save();


public GenericRepository()

context = new Entities();
dbEntity = context.Set<T>();



Services



public class TestService : ITestService

public TestService(
IRepository<User> userRepository
)

_userRepository = userRepository;


private readonly IRepository<User> _userRepository;

public IEnumerable<User> Get()


var result = _userRepository.Get();

return result;




Controller



public class HomeController : Controller

public HomeController(ITestService testService)

_testService = testService;


private readonly ITestService _testService;

public IEnumerable<User> Index()

var result = _testService.Get();

return result;




I found some solution on here (StackOverflow) that I need to add WebApiConfig, I added as below but it also not work. I am getting the output
System.Collections.Generic.List`1[MovieInfo.Core.Models.Models.User]



 public static class WebAppConfig

public static void Register(HttpConfiguration config)

config.Formatters.Remove(new XmlMediaTypeFormatter());

config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;

config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data"));

config.MapHttpAttributeRoutes();

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/controller/action/id",
defaults: new

id = RouteParameter.Optional

);




Here is my Git Repository Link
https://github.com/Harshk16/MovieInfo



Please help me out how to get output in Json Format







c# json asp.net-mvc entity-framework






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 10 at 17:23









Harsh

155




155











  • Where and when are you getting that output ? What is your expected behavior ?
    – Shyju
    Nov 10 at 17:32










  • Instead of inheriting your Home controller with System.Web.Mvc.Controller, you must inherit it with System.Web.Http.ApiController
    – Kundan Singh Chouhan
    Nov 10 at 17:32










  • @Shyju I want last output result as json System.Collections.Generic.List`1[MovieInfo.Core.Models.Models.User] is my output result I also added my git repo link
    – Harsh
    Nov 10 at 17:46











  • @KundanSinghChouhan can you please give me some example,I also added my git repo link above
    – Harsh
    Nov 10 at 17:48
















  • Where and when are you getting that output ? What is your expected behavior ?
    – Shyju
    Nov 10 at 17:32










  • Instead of inheriting your Home controller with System.Web.Mvc.Controller, you must inherit it with System.Web.Http.ApiController
    – Kundan Singh Chouhan
    Nov 10 at 17:32










  • @Shyju I want last output result as json System.Collections.Generic.List`1[MovieInfo.Core.Models.Models.User] is my output result I also added my git repo link
    – Harsh
    Nov 10 at 17:46











  • @KundanSinghChouhan can you please give me some example,I also added my git repo link above
    – Harsh
    Nov 10 at 17:48















Where and when are you getting that output ? What is your expected behavior ?
– Shyju
Nov 10 at 17:32




Where and when are you getting that output ? What is your expected behavior ?
– Shyju
Nov 10 at 17:32












Instead of inheriting your Home controller with System.Web.Mvc.Controller, you must inherit it with System.Web.Http.ApiController
– Kundan Singh Chouhan
Nov 10 at 17:32




Instead of inheriting your Home controller with System.Web.Mvc.Controller, you must inherit it with System.Web.Http.ApiController
– Kundan Singh Chouhan
Nov 10 at 17:32












@Shyju I want last output result as json System.Collections.Generic.List`1[MovieInfo.Core.Models.Models.User] is my output result I also added my git repo link
– Harsh
Nov 10 at 17:46





@Shyju I want last output result as json System.Collections.Generic.List`1[MovieInfo.Core.Models.Models.User] is my output result I also added my git repo link
– Harsh
Nov 10 at 17:46













@KundanSinghChouhan can you please give me some example,I also added my git repo link above
– Harsh
Nov 10 at 17:48




@KundanSinghChouhan can you please give me some example,I also added my git repo link above
– Harsh
Nov 10 at 17:48












2 Answers
2






active

oldest

votes

















up vote
0
down vote



accepted










If you want to return JSON response form your MVC controller action method, you may use the Json method.



The Json method is defined inside System.Web.Mvc.Controller, from which you are inherting your HomeController. So you have access to this method.



The Json method returns JsonResult typw. So make sure your method's return type is either JsonResult or ActionResult. (The JsonResult class inhertis from ActionResult)



public JsonResult Index()

var result = _testService.Get();
return Json(result,JsonRequestBehavior.AllowGet);



Or



public ActionResult Index()

var result = _testService.Get();
return Json(result,JsonRequestBehavior.AllowGet);



Another option is to use a web api controller instead of MVC controller. Register your web api routes before your MVC action method routing in your global.asax.cs



protected void Application_Start()

AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
GlobalConfiguration.Configure(WebAppConfig.Register);

RouteConfig.RegisterRoutes(RouteTable.Routes);

// Your other existing code



and create a webapi controller which inherits from System.Web.Http.ApiController. Here I removed the Dependency Injection part for simplicity. You can wire up DI in your web api controllers by following the AutoFac web api integration tutorial



public class UsersController : ApiController

public IEnumerable<User> Get()

var result = new List<User>

new User Id = Guid.NewGuid() , DisplayName = "Shyju",
new User Id = Guid.NewGuid(), DisplayName = "Scott"
;
// Hard coded list of users.
// Once you fix your DI setup, you can use your service to get data.
return result;




By default, web api uses content negotioation. It reads the "Accept" request header value and based on that execute the corresponding formatter. With your current web api routing template, you can access this endpoint with the below request URL



http://yourSiteBaseUrl/api/users/get


If you do not want the get in your API Urls, simply fix your route template when registering the web api routing



routeTemplate: "api/controller/id"





share|improve this answer






















  • Instead of writing to every controller i want to make it generic
    – Harsh
    Nov 10 at 17:50

















up vote
0
down vote













To use the web api, which you define in your WebApiConfig, your controllers need to inherit from the Web Api base controller ApiController instead of the MVC base controller controller.



When inheriting from the ApiController, the default Formatter will take care of turning your controller methods output to your desire result. In your case, as you removed the Xml-formatter, the default will be Json.



public class HomeController : ApiController

public HomeController(ITestService testService)

_testService = testService;


private readonly ITestService _testService;

public IEnumerable<User> Index()

var result = _testService.Get();

return result;







share|improve this answer




















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













     

    draft saved


    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53241524%2fhow-to-return-json-data-from-mvc-controller-in-c-sharp%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote



    accepted










    If you want to return JSON response form your MVC controller action method, you may use the Json method.



    The Json method is defined inside System.Web.Mvc.Controller, from which you are inherting your HomeController. So you have access to this method.



    The Json method returns JsonResult typw. So make sure your method's return type is either JsonResult or ActionResult. (The JsonResult class inhertis from ActionResult)



    public JsonResult Index()

    var result = _testService.Get();
    return Json(result,JsonRequestBehavior.AllowGet);



    Or



    public ActionResult Index()

    var result = _testService.Get();
    return Json(result,JsonRequestBehavior.AllowGet);



    Another option is to use a web api controller instead of MVC controller. Register your web api routes before your MVC action method routing in your global.asax.cs



    protected void Application_Start()

    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    GlobalConfiguration.Configure(WebAppConfig.Register);

    RouteConfig.RegisterRoutes(RouteTable.Routes);

    // Your other existing code



    and create a webapi controller which inherits from System.Web.Http.ApiController. Here I removed the Dependency Injection part for simplicity. You can wire up DI in your web api controllers by following the AutoFac web api integration tutorial



    public class UsersController : ApiController

    public IEnumerable<User> Get()

    var result = new List<User>

    new User Id = Guid.NewGuid() , DisplayName = "Shyju",
    new User Id = Guid.NewGuid(), DisplayName = "Scott"
    ;
    // Hard coded list of users.
    // Once you fix your DI setup, you can use your service to get data.
    return result;




    By default, web api uses content negotioation. It reads the "Accept" request header value and based on that execute the corresponding formatter. With your current web api routing template, you can access this endpoint with the below request URL



    http://yourSiteBaseUrl/api/users/get


    If you do not want the get in your API Urls, simply fix your route template when registering the web api routing



    routeTemplate: "api/controller/id"





    share|improve this answer






















    • Instead of writing to every controller i want to make it generic
      – Harsh
      Nov 10 at 17:50














    up vote
    0
    down vote



    accepted










    If you want to return JSON response form your MVC controller action method, you may use the Json method.



    The Json method is defined inside System.Web.Mvc.Controller, from which you are inherting your HomeController. So you have access to this method.



    The Json method returns JsonResult typw. So make sure your method's return type is either JsonResult or ActionResult. (The JsonResult class inhertis from ActionResult)



    public JsonResult Index()

    var result = _testService.Get();
    return Json(result,JsonRequestBehavior.AllowGet);



    Or



    public ActionResult Index()

    var result = _testService.Get();
    return Json(result,JsonRequestBehavior.AllowGet);



    Another option is to use a web api controller instead of MVC controller. Register your web api routes before your MVC action method routing in your global.asax.cs



    protected void Application_Start()

    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    GlobalConfiguration.Configure(WebAppConfig.Register);

    RouteConfig.RegisterRoutes(RouteTable.Routes);

    // Your other existing code



    and create a webapi controller which inherits from System.Web.Http.ApiController. Here I removed the Dependency Injection part for simplicity. You can wire up DI in your web api controllers by following the AutoFac web api integration tutorial



    public class UsersController : ApiController

    public IEnumerable<User> Get()

    var result = new List<User>

    new User Id = Guid.NewGuid() , DisplayName = "Shyju",
    new User Id = Guid.NewGuid(), DisplayName = "Scott"
    ;
    // Hard coded list of users.
    // Once you fix your DI setup, you can use your service to get data.
    return result;




    By default, web api uses content negotioation. It reads the "Accept" request header value and based on that execute the corresponding formatter. With your current web api routing template, you can access this endpoint with the below request URL



    http://yourSiteBaseUrl/api/users/get


    If you do not want the get in your API Urls, simply fix your route template when registering the web api routing



    routeTemplate: "api/controller/id"





    share|improve this answer






















    • Instead of writing to every controller i want to make it generic
      – Harsh
      Nov 10 at 17:50












    up vote
    0
    down vote



    accepted







    up vote
    0
    down vote



    accepted






    If you want to return JSON response form your MVC controller action method, you may use the Json method.



    The Json method is defined inside System.Web.Mvc.Controller, from which you are inherting your HomeController. So you have access to this method.



    The Json method returns JsonResult typw. So make sure your method's return type is either JsonResult or ActionResult. (The JsonResult class inhertis from ActionResult)



    public JsonResult Index()

    var result = _testService.Get();
    return Json(result,JsonRequestBehavior.AllowGet);



    Or



    public ActionResult Index()

    var result = _testService.Get();
    return Json(result,JsonRequestBehavior.AllowGet);



    Another option is to use a web api controller instead of MVC controller. Register your web api routes before your MVC action method routing in your global.asax.cs



    protected void Application_Start()

    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    GlobalConfiguration.Configure(WebAppConfig.Register);

    RouteConfig.RegisterRoutes(RouteTable.Routes);

    // Your other existing code



    and create a webapi controller which inherits from System.Web.Http.ApiController. Here I removed the Dependency Injection part for simplicity. You can wire up DI in your web api controllers by following the AutoFac web api integration tutorial



    public class UsersController : ApiController

    public IEnumerable<User> Get()

    var result = new List<User>

    new User Id = Guid.NewGuid() , DisplayName = "Shyju",
    new User Id = Guid.NewGuid(), DisplayName = "Scott"
    ;
    // Hard coded list of users.
    // Once you fix your DI setup, you can use your service to get data.
    return result;




    By default, web api uses content negotioation. It reads the "Accept" request header value and based on that execute the corresponding formatter. With your current web api routing template, you can access this endpoint with the below request URL



    http://yourSiteBaseUrl/api/users/get


    If you do not want the get in your API Urls, simply fix your route template when registering the web api routing



    routeTemplate: "api/controller/id"





    share|improve this answer














    If you want to return JSON response form your MVC controller action method, you may use the Json method.



    The Json method is defined inside System.Web.Mvc.Controller, from which you are inherting your HomeController. So you have access to this method.



    The Json method returns JsonResult typw. So make sure your method's return type is either JsonResult or ActionResult. (The JsonResult class inhertis from ActionResult)



    public JsonResult Index()

    var result = _testService.Get();
    return Json(result,JsonRequestBehavior.AllowGet);



    Or



    public ActionResult Index()

    var result = _testService.Get();
    return Json(result,JsonRequestBehavior.AllowGet);



    Another option is to use a web api controller instead of MVC controller. Register your web api routes before your MVC action method routing in your global.asax.cs



    protected void Application_Start()

    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    GlobalConfiguration.Configure(WebAppConfig.Register);

    RouteConfig.RegisterRoutes(RouteTable.Routes);

    // Your other existing code



    and create a webapi controller which inherits from System.Web.Http.ApiController. Here I removed the Dependency Injection part for simplicity. You can wire up DI in your web api controllers by following the AutoFac web api integration tutorial



    public class UsersController : ApiController

    public IEnumerable<User> Get()

    var result = new List<User>

    new User Id = Guid.NewGuid() , DisplayName = "Shyju",
    new User Id = Guid.NewGuid(), DisplayName = "Scott"
    ;
    // Hard coded list of users.
    // Once you fix your DI setup, you can use your service to get data.
    return result;




    By default, web api uses content negotioation. It reads the "Accept" request header value and based on that execute the corresponding formatter. With your current web api routing template, you can access this endpoint with the below request URL



    http://yourSiteBaseUrl/api/users/get


    If you do not want the get in your API Urls, simply fix your route template when registering the web api routing



    routeTemplate: "api/controller/id"






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 10 at 18:28

























    answered Nov 10 at 17:47









    Shyju

    142k86327432




    142k86327432











    • Instead of writing to every controller i want to make it generic
      – Harsh
      Nov 10 at 17:50
















    • Instead of writing to every controller i want to make it generic
      – Harsh
      Nov 10 at 17:50















    Instead of writing to every controller i want to make it generic
    – Harsh
    Nov 10 at 17:50




    Instead of writing to every controller i want to make it generic
    – Harsh
    Nov 10 at 17:50












    up vote
    0
    down vote













    To use the web api, which you define in your WebApiConfig, your controllers need to inherit from the Web Api base controller ApiController instead of the MVC base controller controller.



    When inheriting from the ApiController, the default Formatter will take care of turning your controller methods output to your desire result. In your case, as you removed the Xml-formatter, the default will be Json.



    public class HomeController : ApiController

    public HomeController(ITestService testService)

    _testService = testService;


    private readonly ITestService _testService;

    public IEnumerable<User> Index()

    var result = _testService.Get();

    return result;







    share|improve this answer
























      up vote
      0
      down vote













      To use the web api, which you define in your WebApiConfig, your controllers need to inherit from the Web Api base controller ApiController instead of the MVC base controller controller.



      When inheriting from the ApiController, the default Formatter will take care of turning your controller methods output to your desire result. In your case, as you removed the Xml-formatter, the default will be Json.



      public class HomeController : ApiController

      public HomeController(ITestService testService)

      _testService = testService;


      private readonly ITestService _testService;

      public IEnumerable<User> Index()

      var result = _testService.Get();

      return result;







      share|improve this answer






















        up vote
        0
        down vote










        up vote
        0
        down vote









        To use the web api, which you define in your WebApiConfig, your controllers need to inherit from the Web Api base controller ApiController instead of the MVC base controller controller.



        When inheriting from the ApiController, the default Formatter will take care of turning your controller methods output to your desire result. In your case, as you removed the Xml-formatter, the default will be Json.



        public class HomeController : ApiController

        public HomeController(ITestService testService)

        _testService = testService;


        private readonly ITestService _testService;

        public IEnumerable<User> Index()

        var result = _testService.Get();

        return result;







        share|improve this answer












        To use the web api, which you define in your WebApiConfig, your controllers need to inherit from the Web Api base controller ApiController instead of the MVC base controller controller.



        When inheriting from the ApiController, the default Formatter will take care of turning your controller methods output to your desire result. In your case, as you removed the Xml-formatter, the default will be Json.



        public class HomeController : ApiController

        public HomeController(ITestService testService)

        _testService = testService;


        private readonly ITestService _testService;

        public IEnumerable<User> Index()

        var result = _testService.Get();

        return result;








        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 10 at 18:27









        Marcus Höglund

        9,32352542




        9,32352542



























             

            draft saved


            draft discarded















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53241524%2fhow-to-return-json-data-from-mvc-controller-in-c-sharp%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            What does pagestruct do in Eviews?

            Dutch intervention in Lombok and Karangasem

            Channel Islands