---
# System prepended metadata

title: ICommonHttpContext 快速取得常用 HttpContext 內容物件
tags: [.NetCore]

---

# ICommonHttpContext 快速取得常用 HttpContext 內容物件
###### tags: `.NetCore`

## ICommonHttpContext
```
public interface ICommonHttpContext {
    public bool IsAuthenticated();
    public string GetUsername();
    public string GetRequestIPAddress();
}
```

## CommonHttpContext
```
public class CommonHttpContext : ICommonHttpContext {

    private readonly IHttpContextAccessor _httpContextAccessor;
    public CommonHttpContext(IHttpContextAccessor httpContextAccessor) {
        _httpContextAccessor = httpContextAccessor;
    }

    public bool IsAuthenticated() {
        return _httpContextAccessor.HttpContext.User == null ? false : _httpContextAccessor.HttpContext.User.Identity.IsAuthenticated;
    }
    public string GetUsername() {
        return _httpContextAccessor.HttpContext.User?.Claims?.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier)?.Value;
    }
    public string GetRequestIPAddress() {
        return _httpContextAccessor.HttpContext.Request?.HttpContext.Connection.RemoteIpAddress?.ToString();
    }
}
```

## Startup.cs 註冊
```
public void ConfigureServices(IServiceCollection services) {
    #region HttpContext
    
    // 應該是為了在 public void Configure 中使用所加
    services.AddHttpContextAccessor(); 
    services.AddScoped<ICommonHttpContext, CommonHttpContext>();

    #endregion
}
```

## 加碼了解如何在 Startup.cs 中的 public void Configure 中使用
```
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ICommonHttpContext commonHttpContext) {

}
```