简体   繁体   中英

Using the same control to return JSON/XML/HTML with Web API MVC4

I am guessing it has been asked before but I did not see it and thought maybe I am missing something fundamental. My question is why can't I have one API controller that bases the format of result on the accepted content format(ie application/json)? Maybe I am being lazy - but I rather do something like if html is the expected result format than let me return a view, if json is the accept format than I can return JSOn -etc... If I have two namespaces, then that is also two methods I have to maintain - when the only difference is the media format.

When you return an object from an action in a web api controller, what is actually going on behind the scenes looks like this:

 public class SessionController : ApiController
    {

        public HttpResponseMessage Get(int id)
        {
            var vm = new SessionDetailViewModel {Speaker = "Bob", Title = "Bob's talk"};

            var conneg = new DefaultContentNegotiator();
            var result = conneg.Negotiate(typeof (SessionDetailViewModel), this.Request,Configuration.Formatters);
            var content = new ObjectContent<SessionDetailViewModel>(vm, result.Formatter,result.MediaType);

            return new HttpResponseMessage() {Content = content};
        }
    }

As long as you have the appropriate set of formatters that can map the returned object to the wire format then conneg will happen automatically.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM