我想试试 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 擅离职守。 (我选择了“自托管”变体)。
我错过了什么?
最佳答案
自托管请引用这篇文章:
您的示例的完整重写代码如下:
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/