Donate

Show Or Get IP Address in ASP.NET MVC

Here's a simple tutorial on how to get a user's IP address using ASP.NET MVC and jQuery. The fetching of record is triggered when the textbox receives focus.
HTML Code
1
<input id="txtID" type="text" />

JavaScript Code
1
2
3
4
5
6
7
8
$(document).ready(function () {
    $('#txtID').focus(function () {            
        $.getJSON('@Url.Action("GetIPAddress","getipaddress")'
                 , function (result) {
            $("#txtID").val(result);
        });
    });
});

C# Code
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
public JsonResult GetIPAddress()
{
    System.Web.HttpContext context = System.Web.HttpContext.Current;
    string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    string output = string.Empty;
 
    if (!string.IsNullOrEmpty(ipAddress))
    {
        string[] addresses = ipAddress.Split(',');
        if (addresses.Length != 0)
        {
            output = addresses[0];
        }
    }
    else
    {
        output = context.Request.ServerVariables["REMOTE_ADDR"];
    }
 
    return Json(output, JsonRequestBehavior.AllowGet);
}  

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

Bootstrap Modal In ASP.NET MVC With CRUD Operations