Webapi计算特定的get请求

时间:2016-01-03 15:41:23

标签: c# asp.net linq rest asp.net-web-api

我有一个拥有不同山脉的数据库,在我的Web Api中,我正在尝试记录IP地址,时间和日期以及特定山峰被访问次数的“计数”。如果用户导航到api/Mountains/1,则应记录该地址的IP地址,日期时间和计数mountain.name。但我有点迷失在逻辑中,我不知道如何计算每一座山?我没有存储这些信息,所以我希望它可以存放在内存中。

编辑:(从回答更新)

  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);
    }

1 个答案:

答案 0 :(得分:1)

如果只需要内存中的计数器数据,则可以使用静态字典。 看看这个

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; }
    }

}