zoukankan      html  css  js  c++  java
  • asp.net core获取HttpContext相关操作

     1 建立类:
     2 
     3 using System;
     4 using System.Collections.Generic;
     5 using System.Linq;
     6 using System.Threading.Tasks;
     7 using Microsoft.AspNetCore.Http;
     8 
     9 namespace Iyibank.Core
    10 {
    11 public static class MyHttpContext
    12 {
    13 public static IServiceProvider ServiceProvider;
    14 
    15 static MyHttpContext()
    16 { }
    17 
    18 
    19 public static HttpContext Current
    20 {
    21 get
    22 {
    23 object factory = ServiceProvider.GetService(typeof(Microsoft.AspNetCore.Http.IHttpContextAccessor));
    24 
    25 HttpContext context = ((IHttpContextAccessor)factory).HttpContext;
    26 return context;
    27 }
    28 }
    29 }
    30 }
    31 
    32 Startup.cs添加如下
    33 
    34  public void ConfigureServices(IServiceCollection services)内容下添加如下
    35 
    36  services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    37 
    38 Configure修改如下
    39 
    40 public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory,IServiceProvider svp)
    41 
    42 Configure下添加以下内容
    43 
    44    Iyibank.Core.MyHttpContext.ServiceProvider = svp;
    45 
    46 这样在其他地方需要使用时,直接调用即可
    47 
    48 /// <summary>
    49 /// 获得当前页面客户端的IP
    50 /// </summary>
    51 /// <returns>当前页面客户端的IP</returns>
    52 public static string GetIP()
    53 {
    54 //try
    55 //{
    56 string result = (MyHttpContext.Current.Request.Headers["HTTP_X_FORWARDED_FOR"].ToString() != null
    57 && MyHttpContext.Current.Request.Headers["HTTP_X_FORWARDED_FOR"] != String.Empty)
    58 ? MyHttpContext.Current.Request.Headers["HTTP_X_FORWARDED_FOR"]
    59 : MyHttpContext.Current.Request.Headers["REMOTE_ADDR"];
    60 // string result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
    61 if (string.IsNullOrEmpty(result))
    62 result = MyHttpContext.Current.Request.Headers["HTTP_X_FORWARDED_FOR"];
    63 
    64 if (string.IsNullOrEmpty(result) || !Utils.IsIP(result))
    65 return "127.0.0.1";
    66 
    67 return result;
    68 //}
    69 //catch
    70 //{
    71 // return "127.0.0.1";
    72 //}
    73 }
  • 相关阅读:
    洛谷P5113 Sabbat of the witch
    「学习笔记」洲阁筛
    【UNR #3】百鸽笼
    LOJ#6703. 小 Q 的序列
    python数组字符串还原为数组
    QGIS导入excel点数据
    QGIS统计面要素中包含的点要素数量
    gpd.read_file(),报错路径在系统文件中不存在
    QGIS平移要素
    QGIS多部件面转单部件面
  • 原文地址:https://www.cnblogs.com/lyl6796910/p/6648821.html
Copyright © 2011-2022 走看看