c# - ASP.NET WebAPI 中 HttpServiceHost 的等价物是什么?

标签 c# wcf-web-api asp.net-web-api

我想试试 this自托管网络服务示例(最初使用 WCF WebApi 编写),但使用新的 ASP.NET WebAPI(它是 WCF WebApi 的后代)。

using System;
using System.Net.Http;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using Microsoft.ApplicationServer.Http;

namespace SampleApi {
    class Program {
        static void Main(string[] args) {
            var host = new HttpServiceHost(typeof (ApiService), "http://localhost:9000");
            host.Open();
            Console.WriteLine("Browse to http://localhost:9000");
            Console.Read();
        }
    }

    [ServiceContract]
    public class ApiService {    
        [WebGet(UriTemplate = "")]
        public HttpResponseMessage GetHome() {
            return new HttpResponseMessage() {
                Content = new StringContent("Welcome Home", Encoding.UTF8, "text/plain")
            };    
        }
    }    
}

但是,要么我没有安装正确的 NuGotten 包,要么 HttpServiceHost 擅离职守。 (我选择了“自托管”变体)。

我错过了什么?

最佳答案

自托管请引用这篇文章:

Self-Host a Web API (C#)

您的示例的完整重写代码如下:

class Program {

    static void Main(string[] args) {

        var config = new HttpSelfHostConfiguration("http://localhost:9000");

        config.Routes.MapHttpRoute(
            "API Default", "api/{controller}/{id}", 
            new { id = RouteParameter.Optional }
        );

        using (HttpSelfHostServer server = new HttpSelfHostServer(config)) {

            server.OpenAsync().Wait();

            Console.WriteLine("Browse to http://localhost:9000/api/service");
            Console.WriteLine("Press Enter to quit.");

            Console.ReadLine();
        }

    }
}

public class ServiceController : ApiController {    

    public HttpResponseMessage GetHome() {

        return new HttpResponseMessage() {

            Content = new StringContent("Welcome Home", Encoding.UTF8, "text/plain")
        };    
    }
}

希望这对您有所帮助。

关于c# - ASP.NET WebAPI 中 HttpServiceHost 的等价物是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9630677/

相关文章:

C# 打印空格/缩进

c# - 具有透明状态栏的 Xamarin Forms 背景图像

.net - 有没有办法使用 WCF Web API 控制 JSON 格式?

c# - 调用 HttpRequest.GetBufferlessInputStream 后不支持此方法或属性

c# - ASP.NET WebAPI 2 嵌套 JSON

c# - 访问 ASP.NET Core Controller 中的连接字符串

c# - 如何在 Swashbuckle 中更改 POST 和 PUT 的必填字段?

javascript - 跨站点 ajax 请求不起作用

c# - 如何使用Elasticsearch索引多字段元素