G Gr
G Gr

Reputation: 6090

Webapi counting specific get requests

I have a database that holds different mountains and in my Web Api I am trying to log the IP address, Time and Date and the "Count" of how many times a specific mountain has been accessed. If a user navigates to api/Mountains/1 then it should log the ip address, datetime and a count for that specific mountain.name. But I am kind of lost in the logic and I dont know how to count each individual mountain? I am not storing this information, so I was hoping it could just be held in memory.

EDIT: (Updated from answer)

  public class MountainsController : ApiController
    {
    private MountainContext db = new MountainContext();
    private int Count;

    static Dictionary<int, string> data;
    static Dictionary<int, int> dataCounter;

    static MountainsController()
    {
        data = Enumerable.Range(1, 10).ToDictionary(i => i, i => "Mountain " + i.ToString());
        dataCounter = Enumerable.Range(1, 10).ToDictionary(i => i, i => 0);
    }
    // GET: api/Mountains/5
    [ResponseType(typeof(Mountain))]
    public async Task<IHttpActionResult> GetMountain(int id)
    {
        Mountain mountain = await db.Mountains.FindAsync(id);
        if (mountain == null)
        {
            return NotFound();
        }
        if (mountain != null)
        {
            string mountainName = data[id];
            dataCounter[id] = dataCounter[id] + 1;
            Count = dataCounter[id];
            var host = ((System.Web.HttpContextWrapper)Request.Properties["MS_HttpContext"]).Request.UserHostAddress + "," + mountain.Name + "," + DateTime.Now + "," + Count;
            System.IO.File.AppendAllText(@"C:\myfile.txt", host);
        }

        return Ok(mountain);
    }

Upvotes: 2

Views: 2283

Answers (1)

George Vovos
George Vovos

Reputation: 7618

If you need the counter data only in memory you can use a static dictionary. Have a look at this

using System.Collections.Generic;
using System.Web.Http;
using System.Linq;

namespace WebApplication3.Areas.api.Controllers
{
    public class MountainController : ApiController
    {
        static Dictionary<int, string> data;
        static Dictionary<int, int> dataCounter;

        static MountainController()
        {
            data = Enumerable.Range(1, 10).ToDictionary(i => i, i => "Mountain " + i.ToString());
            dataCounter = Enumerable.Range(1, 10).ToDictionary(i => i, i => 0);
        }
        [HttpGet]
        public MountainModel GetMountain(int id)
        {
            string mountainName = data[id];

            dataCounter[id] = dataCounter[id] + 1;
            return new MountainModel() { Id = id, Name = mountainName, Count = dataCounter[id] };
        }
    }
    public class MountainModel
    {
        public int Count { get; set; }
        public int Id { get; set; }
        public string Name { get; set; }
    }

}

Upvotes: 1

Related Questions