为什么 IHttpContextAccessor 在 Blazor 服务器端总是得到空 IP? [英] Why IHttpContextAccessor always get null IP in Blazor server-side?

查看:22
本文介绍了为什么 IHttpContextAccessor 在 Blazor 服务器端总是得到空 IP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的 SDK 是 5.0.100-rc.2.20479.15.

The SDK I am using is 5.0.100-rc.2.20479.15.

目标框架也是.Net 5.

The target framework also is .Net 5.

这是我在startup.cs中的代码:

Here is my code in startup.cs:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;

namespace Sample
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddServerSideBlazor();            
            services.AddHttpContextAccessor();            
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Error");
            }

            app.UseStaticFiles();

            app.UseRouting();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapBlazorHub();
                endpoints.MapFallbackToPage("/_Host");
            });
        }
    }
}

这是我在 index.razor 中的代码:

And here is my code in index.razor:

@page "/"
@inject IHttpContextAccessor httpContextAccessor


<h1>@IP</h1>
@code{    
    public string IP{get;set;}
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if (firstRender)
        {
          IP=httpContextAccessor.HttpContext.Connection?.RemoteIpAddress.ToString();
        }
    }
}

我把它发布到服务器计算机,IP总是返回空.

I published it to the server computer and the IP always returns null.

我的程序需要提交一个表单.并且表单只允许同一个人每天提交一次(没有帐户).

My program needs to submit a form. And the form is only allowed to submit once per day by the same people(without an account).

所以我需要获取 IP 并设置一个 IMemoryCache 和一个为期一天的 DateTimeOffset.

So I need to get the IP and set an IMemoryCache with a one-day DateTimeOffset.

尽管如此,存储 IP 地址并不是解决我的功能的完美方法,但似乎我只能这样做.

In spite, storing the IP address is not a perfect way to solve my feature but it seems I can only do it like this.

推荐答案

警告:@enet 评论表明这不是在 Blazor 中进行此操作的推荐方法

WARNING: AS @enet comment suggests this is not the recommended way to go about this in Blazor

以防它对任何人有帮助...这是我对@Melon NG 建议的解释

In case it helps anyone... Here is my interpretation of @Melon NG's suggestion

在_Host.cshtml.cs

In _Host.cshtml.cs

using AutoCheck.BlazorApp.Components;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.RazorPages;


namespace AutoCheck.BlazorApp.Pages
{
    public class Host : PageModel
    {
        private readonly IHttpContextAccessor _httpContextAccessor;
        private readonly IRememberMe _rememberMe;

        public Host(IHttpContextAccessor httpContextAccessor, IRememberMe rememberMe)
        {
            _rememberMe = rememberMe;
            _httpContextAccessor = httpContextAccessor;
        }

        public void OnGet()
        {
            _rememberMe.RemoteIpAddress = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress;
            
        }
    }
}

记住我

using System.Net;

namespace AutoCheck.BlazorApp.Components
{
    public interface IRememberMe
    {
        public IPAddress RemoteIpAddress { get; set; }
    }

    public class RememberMe : IRememberMe
    {
        public IPAddress RemoteIpAddress { get; set; }
    }
}

关于.razor

@page "/About"
@inject IRememberMe RememberMe


<h3>About</h3>

<table class="table table-striped">
    <thead>
    <td>Item</td>
    <td>Value</td>
    </thead>
 
    <tr>
        <td>Remote IP</td>
        <td>@RememberMe.RemoteIpAddress</td>
    </tr>
    
</table>

在 Startup.cs 的 ConfigureServices 中

In ConfigureServices in Startup.cs

public void ConfigureServices(IServiceCollection services)
{
...
//services.AddSingleton<IRememberMe, RememberMe>();
services.AddScoped<IRememberMe, RememberMe>();
...
}

这篇关于为什么 IHttpContextAccessor 在 Blazor 服务器端总是得到空 IP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆