【问题标题】:What is the equivalent of HttpServiceHost in ASP.NET WebAPI?ASP.NET WebAPI 中的 HttpServiceHost 等价物是什么?
【发布时间】:2012-03-26 16:54:21
【问题描述】:

我想尝试this 自托管 Web 服务的示例(最初用 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 擅离职守。 (我选择了“自托管”变体)。

我错过了什么?

【问题讨论】:

  • This 帮助我完成了一些工作,但它看起来不像是严格的等价物。

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


【解决方案1】:

自托管请参考这篇文章:

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")
        };    
    }
}

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-24
    • 2017-07-24
    • 2018-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-24
    • 1970-01-01
    相关资源
    最近更新 更多