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

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

问题描述

我有一个简单的.net核心网络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运行,我会得到

If I run this via dotnet run I get

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 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天全站免登陆