• asp.net core获取HttpContext相关操作


    建立类:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Http;

    namespace Iyibank.Core
    {
    public static class MyHttpContext
    {
    public static IServiceProvider ServiceProvider;

    static MyHttpContext()
    { }


    public static HttpContext Current
    {
    get
    {
    object factory = ServiceProvider.GetService(typeof(Microsoft.AspNetCore.Http.IHttpContextAccessor));

    HttpContext context = ((IHttpContextAccessor)factory).HttpContext;
    return context;
    }
    }
    }
    }

    Startup.cs添加如下

     public void ConfigureServices(IServiceCollection services)内容下添加如下

     services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    Configure修改如下

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory,IServiceProvider svp)

    Configure下添加以下内容

       Iyibank.Core.MyHttpContext.ServiceProvider = svp;

    这样在其他地方需要使用时,直接调用即可

    /// <summary>
    /// 获得当前页面客户端的IP
    /// </summary>
    /// <returns>当前页面客户端的IP</returns>
    public static string GetIP()
    {
    //try
    //{
    string result = (MyHttpContext.Current.Request.Headers["HTTP_X_FORWARDED_FOR"].ToString() != null
    && MyHttpContext.Current.Request.Headers["HTTP_X_FORWARDED_FOR"] != String.Empty)
    ? MyHttpContext.Current.Request.Headers["HTTP_X_FORWARDED_FOR"]
    : MyHttpContext.Current.Request.Headers["REMOTE_ADDR"];
    // string result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
    if (string.IsNullOrEmpty(result))
    result = MyHttpContext.Current.Request.Headers["HTTP_X_FORWARDED_FOR"];

    if (string.IsNullOrEmpty(result) || !Utils.IsIP(result))
    return "127.0.0.1";

    return result;
    //}
    //catch
    //{
    // return "127.0.0.1";
    //}
    }

  • 相关阅读:
    SpringBoot开发中的坑 记录一些
    MongoDB 文档【行】
    MongoDB 集合【表】
    MongoDB 数据库
    MongoDB 基础
    gitlab或github下fork后如何同步源的新更新内容?
    解决:android源码同步repo sync 时出现的fatal:duplicate path错误
    android ROM刷机updater-script单刷补丁包脚本
    一键解包/打包boot.img/recovery.img工具(高通/MTK双版 支持android 5.1以上)
    解决:github上传时出现error: src refspec master does not match any
  • 原文地址:https://www.cnblogs.com/zhangkjun/p/6143388.html
Copyright © 2020-2023  润新知