c# – 远程连接到.net核心自托管的web api

前端之家收集整理的这篇文章主要介绍了c# – 远程连接到.net核心自托管的web api前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个简单的.net核心web api,只有一个动作:
[Route("[action]")]
public class APIController : Controller
{
    // GET api/values
    [HttpGet]
    public string Ping()
    {
        return DateTime.Now.ToString();
    }
}

如果我通过dotnet运行这个运行,我得到

Hosting environment: Production
Content root path: C:\Users\xxx\Documents\Visual Studio 2015\Projects\SelfHostTest\src\SelfHostTest
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.

转到浏览器并输入http://localhost:5000/ping会导致成功返回当前时间.但是,转到远程计算机(相同的LAN)并尝试通过http://odin:5000/ping访问服务会导致404错误. (Odin是通过dotnet运行在控制台中运行web api的机器的名称).

服务器(和客户端!)防火墙都已关闭.我可以成功地ping“odin”.

任何想法我在这里缺少什么简单的步骤.我在家里和工作中都尝试过这个但没有成功.

@H_502_15@解决方法
我的猜测是问题不在你的控制器中,而是在program.cs中.您需要修改WebHost的构造
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseUrls("http://localhost:5000","http://odin:5000","http://192.168.1.2:5000")
.UseIISIntegration()
.UseStartup<Startup>()
.Build();

除非你添加UseUrls行,否则Kestrel不会在localhost之外监听.这是有道理的,因为在正常情况下,Kestrel将坐在IIS或NGNIX等反向代理之后,不需要绑定到外部URL.

原文链接:https://www.f2er.com/csharp/100471.html

猜你在找的C#相关文章