WEB API 2自托管的主机名问题

7

我正在尝试创建一个自托管的Web API服务。我遵循了一篇教程,它在我的本地计算机上运行良好。

localhost/api/values响应正常,返回预期的JSON数据。

现在,我有一个绑定到DNS“myserver.mycompany.com”的服务器。当我在此服务器上启动我的WebApi 2服务并尝试调用myserver.mycompany.com/api/values时,出现404页面未找到错误。

如果我在此服务器上本地浏览并调用localhost/api/values URL,则正常工作。

以下是Startup类的代码:

using Owin;
using System.Web.Http;

namespace SelfHostedWebApi2
{
public class Startup
{
    // This code configures Web API. The Startup class is specified as a type
    // parameter in the WebApp.Start method.
    public void Configuration(IAppBuilder appBuilder)
    {
        // Configure Web API for self-host. 
        HttpConfiguration config = new HttpConfiguration();
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        appBuilder.UseWebApi(config);
    }
}
}

以下是我启动服务器的方法:

using Microsoft.Owin.Hosting;
using System;
using System.Net.Http;

namespace SelfHostedWebApi2 
{ 
public class Program 
{ 
    static void Main() 
    { 
        string baseAddress = "http://localhost:80/"; 

        // Start OWIN host 
        try
        {
            WebApp.Start<Startup>(new StartOptions(url: baseAddress));

            HttpClient client = new HttpClient();

            var response = client.GetAsync(baseAddress + "api/values").Result;

            Console.WriteLine(response);
            Console.WriteLine(response.Content.ReadAsStringAsync().Result); 

        }
        catch (Exception ee)
        {

            Console.WriteLine("Erreur : " + ee.ToString());
        }

        Console.ReadLine(); 
    } 
} 
} 

谢谢您的帮助。
1个回答

14

您应该更改baseAddress,使其端点与您的主机名匹配,或者可以使用WeakWildcard * 来匹配所有可能的主机名。

以下代码应该可行:string baseAddress = "http://*:80/";


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接