How to enable your ASP.NET MVC5 application for Web API
There are several tutorials on the internet, but I decided to do something very brief as a response. The rest is as a source of consultation.
1. Global.asax.Cs
Open your Global.asax.cs
and modify it to have the line pointed below:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
// Acrescente a linha abaixo.
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AuthConfig.RegisterAuth();
// Comente a linha abaixo se ela existir.
// WebApiConfig.Register(GlobalConfiguration.Configuration);
}
}
2. /App_start/Webapiconfig.Cs
Create the file WebApiConfig.cs
if it does not exist. Check if it has the following content:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
GlobalConfiguration.Configuration.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);
// Essas linhas abaixo não são obrigatórias, mas elas garantem
// que sempre vou devolver JSON.
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
}
}
3. Create a Controller
In my projects, I usually define a directory called APIControllers
to separate what is Controller
of the MVC site and the Web API. In this directory of your project, right click, choose Add > Controller. The following screen should appear:
Choose the option Web API 2 Controller with Actions, using Entity Framework.
Name it on the next screen and set a few more things:
Define the Model that will be used to generate the Controller
and the data context used (has the option to generate another context if necessary). Click OK.
Your Controller
will be generated with something like this:
public class ProductsController : ApiController
{
private MeuProjetoContext db = new MeuProjetoContext ();
// GET api/Products
public IQueryable<Product> GetProducts()
{
return db.Products;
}
// GET api/Products/5
[ResponseType(typeof(Product))]
public async Task<IHttpActionResult> GetProduct(Guid id)
{
Product product = await db.Products.FindAsync(id);
if (product == null)
{
return NotFound();
}
return Ok(product);
}
// PUT api/Products/5
public async Task<IHttpActionResult> PutProduct(Guid id, Product product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != product.ProductId)
{
return BadRequest();
}
db.Entry(product).State = EntityState.Modified;
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST api/Products
[ResponseType(typeof(Product))]
public async Task<IHttpActionResult> PostProduct(Product product)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Products.Add(product);
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateException)
{
if (ProductExists(product.ProductId))
{
return Conflict();
}
else
{
throw;
}
}
return CreatedAtRoute("DefaultApi", new { id = product.ProductId }, product);
}
// DELETE api/Products/5
[ResponseType(typeof(Product))]
public async Task<IHttpActionResult> DeleteProduct(Guid id)
{
Product product = await db.Products.FindAsync(id);
if (product == null)
{
return NotFound();
}
db.Products.Remove(product);
await db.SaveChangesAsync();
return Ok(product);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool ProductExists(Guid id)
{
return db.Products.Count(e => e.ProductId == id) > 0;
}
}
This is already enough for your system to answer requests by address:
api/Products
You say, Web API?
– Leonel Sanches da Silva
I need a webservice, if Web API is the same thing as this then hehe is worth, I need it to be in non-xml JSON.
– Luiz Negrini
So it’s Web API or REST API. I’ll put a script for you.
– Leonel Sanches da Silva
Okay, I’m on hold and it’s been worth it since!
– Luiz Negrini