.net core 无法用ip地址访问的问题及解决

服务器放在阿里云,且是用开发模式启动的,(dotnet run xxx.csproj),发现通过ip地址怎么也无法访问,以为是防火墙的问题,阿里云防火墙的端口确实是已经开了的,服务器的防火墙也开了,那是什么原因呢?

后来发现控制台提示

从 C:\xxx\Properties\launchSettings.json 使用启动设置...

Hosting environment: Development
           Content root path: C:\xxx
           Now listening on: http://localhost:5000

意识到 launchSettings.json   里的 ip 配为了 localhost ,然后把 http://localhost:5000/ 改成 http://*:5000/

终于解决。

---------------2023/1/6----------------------------------------------------------------------------

.net6了,现在这样写更方便

Program.cs里面

builder.WebHost.UseUrls(WebHelper.get_item("use_url"));

use_url 配置的是 http://*:5000

  • 10
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 14
    评论
要配置.NET Core Web API允许特定IP地址访问,可以在应用程序启动时添加中间件。以下是一个示例中间件,它将允许特定IP地址访问。 ```csharp using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using System.Net; using System.Threading.Tasks; public class IpRestrictionMiddleware { private readonly RequestDelegate _next; private readonly ILogger<IpRestrictionMiddleware> _logger; private readonly string[] _allowedIpAddresses; public IpRestrictionMiddleware(RequestDelegate next, ILogger<IpRestrictionMiddleware> logger, string[] allowedIpAddresses) { _next = next; _logger = logger; _allowedIpAddresses = allowedIpAddresses; } public async Task Invoke(HttpContext context) { var remoteIpAddress = context.Connection.RemoteIpAddress; if (_allowedIpAddresses.Contains(remoteIpAddress.ToString())) { await _next.Invoke(context); } else { _logger.LogWarning($"Request from {remoteIpAddress} rejected."); context.Response.StatusCode = (int)HttpStatusCode.Forbidden; await context.Response.WriteAsync("You are not authorized to access this resource."); } } } public static class IpRestrictionMiddlewareExtensions { public static IApplicationBuilder UseIpRestriction(this IApplicationBuilder builder, string[] allowedIpAddresses) { return builder.UseMiddleware<IpRestrictionMiddleware>(allowedIpAddresses); } } ``` 在`Startup.cs`文件中,可以使用以下代码将中间件添加到管道中: ```csharp public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // ... app.UseIpRestriction(new[] { "127.0.0.1", "::1" }); // add IP addresses to allow // ... } ``` 在上面的示例中,`IpRestrictionMiddleware`类将检查传入请求的远程IP地址,并与允许的IP地址列表进行比较。如果IP地址存在于列表中,则请求将被转发到下一个中间件。否则,请求将被拒绝,并返回HTTP状态码403(Forbidden)和错误消息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ying1979

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值