远程连接到 .net core 自托管 web api [英] Remotely connect to .net core self hosted web api

查看:26
本文介绍了远程连接到 .net core 自托管 web api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 .net core web api,只需一个动作:

I have a simple .net core web api with one action:

[Route("[action]")]
public class APIController : Controller
{
    // GET api/values
    [HttpGet]
    public string Ping()
    {
        return DateTime.Now.ToString();
    }
}

如果我通过 dotnet run 运行它,我会得到

If I run this via dotnet run I get

Hosting environment: Production
Content root path: C:UsersxxxDocumentsVisual Studio 2015ProjectsSelfHostTestsrcSelfHostTest
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.

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

Going to the browser and typing in http://localhost:5000/ping results in a successful return of the current time. However going to a remote machine (same LAN) and trying to access the service via http://odin:5000/ping results in a 404 error. (Odin is the name of the machine running the web api in a console via dotnet run).

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

Both server (and client!) firewalls are turned off. I can ping "odin" successfully.

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

Any ideas what simple step I am missing here. I've tried this at home and at work with no success.

推荐答案

我猜测问题不在您的控制器中,而是在 program.cs 中.您需要修改您的 WebHost 的构造

My guess is that the issue isn't in your controller, it is in program.cs. You need to modify the construction of your 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.

Unless you add the UseUrls line, Kestrel isn't going to listen outside of localhost. This makes sense, because in a normal situation Kestrel will be sitting behind a reverse proxy like IIS or NGNIX and doesn't need to bind to external URLs.

这篇关于远程连接到 .net core 自托管 web api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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