asp.net core擷取HttpContext相關操作

來源:互聯網
上載者:User

標籤:cto   collect   bank   add   server   stat   headers   environ   variable   

建立類:

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";
//}
}

asp.net core擷取HttpContext相關操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.