Create Web Service by reusing code from an already published site. Good practices in Asp.NET MVC

2

I need to create a web service in JSON reusing the maximum code my site has, but I do not know how to do it, if I should add a solution in my site project etc. I can not abstract the idea, I need to after that access it from a Windows Phone application which is also C #. I need you to post examples and best practices, preferably using the NewtonSoft library.

    
asked by anonymous 06.06.2014 / 02:13

1 answer

4

Roadmap of 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 succinct as an answer. The rest is the source of the query.

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. Make sure 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 from the MVC site and the Web API. In this directory of your project, right-click, choose Add > Controller . The following screen should appear:

ChooseWebAPI2ControllerwithActions,usingEntityFramework.

Giveitanameonthenextscreenanddefineafewmorethings:

Define the Model that will be used to generate the Controller and the data context used (you have 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 enough for your system to respond to requests by the address:

  

api / Products

    
06.06.2014 / 03:19