สร้างโปรเจ็กส์ทดสอบแบบ WebApplication แล้วเลือก API ตั้งชื่อ WebApi
ทำการ inject HttpContextAccessor ในไฟล์ Startup.cs
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace WebApi { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
เพิ่ม API Controller ชื่อ ValuesController.cs
ประกาศตัวแปร httpContextAccessor
และกำหนดค่าให้ตัวแปรใน Constructor
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; namespace WebApi.Controllers { [Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase { private readonly IHttpContextAccessor httpContextAccessor; public ValuesController(IHttpContextAccessor httpContextAccessor) { this.httpContextAccessor = httpContextAccessor; } // GET: api/<ValuesController> [HttpGet] public IEnumerable<string> Get() { string clientIpAddress = this.httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString(); return new string[] { "clientIpAddress ", clientIpAddress }; } } }
รันโปรแกรมแล้วลองเรียกไปที่ http://localhost:58691/api/values
จะได้
["clientIpAddress ","::1"]
ถ้าจะจัดเก็บค่า IP Address ลง database ก็กำหนด ขนาด field ไว้ที่ 45 characters
Link