【发布时间】:2021-02-08 07:17:42
【问题描述】:
我使用的 SDK 是 5.0.100-rc.2.20479.15。
目标框架也是.Net 5。
这是我在 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 中的代码:
@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总是返回null。
我的程序需要提交一个表单。并且表格只允许同一个人每天提交一次(没有帐户)。
所以我需要获取 IP 并设置一个 IMemoryCache 和一天的 DateTimeOffset。
尽管如此,存储 IP 地址并不是解决我的功能的完美方法,但似乎我只能这样做。
【问题讨论】:
标签: asp.net-core .net-core blazor blazor-server-side