When and how to use asp.net web api

2

I've been studying Asp.net MVC for some time, I've read about WebApi but I still can not figure out when and how I can use it.

Ex: I have a small news system, where I have a area where the administrative part and the root project the site itself.

How can I use WebApi in this scenario or scenario and is it best to use it?

    
asked by anonymous 04.07.2014 / 05:45

1 answer

1

I do not see much usability for this scenario that you mentioned, but you can use it.

If your application is a SPA (Single Page Applications), that is, it has only one page, yes it should use WebApi, because it is common in this application to use Ajax in which you will return to the client only what is necessary, in other words, the information is already treated and I will only show the user what he requested.

In this type of application data consumption should be lower, which can also be applied to services that will be made available to mobile devices.

Returning to your scenario with the administrative module, you can do the publication of the news via Ajax , in which case you would use POST and the return could be a boolean indicating: Yes a matter was published ( True ); Failed to publish the article ( False ); in this case you would receive the data, would treat in your javascript and would show in a user friendly way, all without updating the page. The possibilities would be endless, it depends on your knowledge.

I use WebApi to return data in Json and even the HTML ready, I decrease and very much load the data.

I said little and you may not have understood the real usability yet, so come on.

Imagine the following scenario, I own a site that provides an Api for you to retrieve banding information. It would work as follows, the user sends me the artist / band and I return it to him in json / xml info about the artist.

Controller

public class ArtistaController : ApiController {
    public Artista Get(string artista) {
       Artista artista = new Artista();      
       .... minha lógica, com modelos etc...
       return artista;
    }
}

The request url (GET) would be: http://meuexemplo.com/Api/Artista/Nome_do_Artista

And suppose I have the ready model of the Artist object, that would be the return in json

My request url for the band Alexisonfire http://meuexemplo.com/Api/Artista/Alexisonfire

Return

  

["Artist": "Alexisonfire", "Genre": "Post Hardcore"}]

And by the end who requested can adapt the information to his application.

Complementary Tips

Return HTML on the Controller without WebAPi

    public ActionResult Index()
    {
        return View();
    }

    [ActionName("Index")]
    [HttpPost]
    public ActionResult PartialIndex()
    {
        return PartialView();
    }

Note that I'm using [HttpPost] , this means that every time I submit a Post it will return me to View Partial and not the entire View.

I hope you have understood.

    
04.07.2014 / 14:07