Ben*_*jol 7 c# wcf-web-api asp.net-web-api
我想尝试这个自托管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")
};
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,要么我没有NuGotten正确的包,要么HttpServiceHost是AWOL.(我选择了'自托管'变体).
我错过了什么?
tug*_*erk 10
请参阅此文章以进行自托管:
您的示例的完整重写代码如下:
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")
};
}
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.