Webapi计数特定的get请求

本文关键字:get 请求 Webapi | 更新日期: 2023-09-27 18:28:58

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

编辑:(根据答案更新)

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

Webapi计数特定的get请求

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

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