本文整理汇总了C#中System.Web.Http.SelfHost.HttpSelfHostServer.CloseAsync方法的典型用法代码示例。如果您正苦于以下问题:C# HttpSelfHostServer.CloseAsync方法的具体用法?C# HttpSelfHostServer.CloseAsync怎么用?C# HttpSelfHostServer.CloseAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Web.Http.SelfHost.HttpSelfHostServer
的用法示例。
在下文中一共展示了HttpSelfHostServer.CloseAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
static void Main(string[] args)
{
HttpSelfHostServer server = null;
try
{
// 设置selfhost
HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(_baseAddress);
//配置(config);
//清除xml格式,设置Json格式
config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
//设置路由
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// 创建服务
server = new HttpSelfHostServer(config);
// 开始监听
server.OpenAsync().Wait();
Console.WriteLine("Listening on " + _baseAddress);
Console.WriteLine("Web API host started...");
//输入exit按Enter結束httpServer
string line = null;
do
{
line = Console.ReadLine();
}
while (line != "exit");
//结束连接
server.CloseAsync().Wait();
}
catch (Exception e)
{
Console.WriteLine("Could not start server: {0}", e.GetBaseException().Message);
Console.WriteLine("Hit ENTER to exit...");
Console.ReadLine();
}
finally
{
if (server != null)
{
// Stop listening
server.CloseAsync().Wait();
}
}
}
示例2: Main
static void Main(string[] args)
{
var port = ConfigurationManager.AppSettings["Port"] ?? "8080";
var hostname = ConfigurationManager.AppSettings["Hostname"] ?? "localhost";
//The url that the service can be called on
var serviceUrl = string.Format("http://{0}:{1}", hostname, port);
//Service configuration
var config = new HttpSelfHostConfiguration(serviceUrl);
//Add routes to controllers
config.Routes.MapHttpRoute("DefaultApi ", "api/{controller}/{id}", new { id = RouteParameter.Optional });
//Writes list of available mediatype formatters to console
Console.WriteLine("{0}{1}", "Registered media type formatters:\n", string.Join("\n", config.Formatters.Select(x => x.GetType())));
//Initialize server
_selfHostServerServer = new HttpSelfHostServer(config);
//Start server
_selfHostServerServer.OpenAsync().Wait();
Console.WriteLine("{1}Self hosting server is running on: {0}", serviceUrl, Environment.NewLine);
Console.WriteLine("Press Enter to quit.");
Console.ReadLine();
//Wires up application close handler
AppDomain.CurrentDomain.ProcessExit += (s, e) =>
{
//Close server
_selfHostServerServer.CloseAsync();
_selfHostServerServer.Dispose();
};
}
示例3: Main
static void Main(string[] args)
{
var baseurl = new Uri("http://localhost:9000/");
var config = new HttpSelfHostConfiguration(baseurl);
//config.MessageHandlers.Add(new GitHubApiRouter(baseurl));
//config.Routes.Add("default", new TreeRoute("",new TreeRoute("home").To<HomeController>(),
// new TreeRoute("contact",
// new TreeRoute("{id}",
// new TreeRoute("address",
// new TreeRoute("{addressid}").To<ContactAddressController>())
// ).To<ContactController>())
// )
// );
var route = new TreeRoute("api");
route.AddWithPath("home", r => r.To<HomeController>());
route.AddWithPath("contact/{id}",r => r.To<ContactController>());
route.AddWithPath("contact/{id}/adddress/{addressid}", r => r.To<ContactAddressController>());
route.AddWithPath("act/A", r => r.To<ActionController>().ToAction("A"));
route.AddWithPath("act/B", r => r.To<ActionController>().ToAction("B"));
config.Routes.Add("default", route);
var host = new HttpSelfHostServer(config);
host.OpenAsync().Wait();
Console.WriteLine("Host open. Hit enter to exit...");
Console.Read();
host.CloseAsync().Wait();
}
示例4: Main
static void Main(string[] args)
{
HttpSelfHostServer server = null;
try {
// Set up server configuration
HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(BaseAddress);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Create server
server = new HttpSelfHostServer(config);
// Start listening
server.OpenAsync().Wait();
Console.WriteLine("Listening on " + BaseAddress);
Console.ReadLine();
}
catch (Exception e) {
Console.WriteLine("Could not start server: {0}", e.GetBaseException().Message);
Console.WriteLine("Hit ENTER to exit...");
Console.ReadLine();
}
finally {
if (server != null) {
// Stop listening
server.CloseAsync().Wait();
}
}
}
示例5: Main
private static void Main(string[] args) {
string prefix = "http://localhost:8080";
HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(prefix);
config.Routes.MapHttpRoute("Default", "{controller}/{action}");
// Append our custom valueprovider to the list of value providers.
config.Services.Add(typeof (ValueProviderFactory), new HeaderValueProviderFactory());
HttpSelfHostServer server = new HttpSelfHostServer(config);
server.OpenAsync().Wait();
try {
// HttpClient will make the call, but won't set the headers for you.
HttpClient client = new HttpClient();
var response = client.GetAsync(prefix + "/ValueProviderTest/GetStuff?id=20").Result;
// Browsers will set the headers.
// Loop. You can hit the request via: http://localhost:8080/Test2/GetStuff?id=40
while (true) {
Thread.Sleep(1000);
Console.Write(".");
}
}
finally {
server.CloseAsync().Wait();
}
}
示例6: Main
static void Main(string[] args)
{
HttpSelfHostServer server = null;
try
{
HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(baseAddress);
config.HostNameComparisonMode = HostNameComparisonMode.Exact;
// Register default route
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}"
);
server = new HttpSelfHostServer(config);
server.OpenAsync().Wait();
Console.WriteLine("Listening on " + baseAddress);
Console.WriteLine("Hit ENTER to exit...");
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("Could not start server: {0}", e.GetBaseException().Message);
Console.WriteLine("Hit ENTER to exit...");
Console.ReadLine();
}
finally
{
if (server != null)
{
server.CloseAsync().Wait();
}
}
}
示例7: Main
public static void Main(string[] args)
{
HttpSelfHostServer server = null;
try
{
var config = new HttpSelfHostConfiguration("http://localhost:3002/")
{
};
//config.Formatters.Add(new HtmlMediaTypeFormatter());
var todoList = new Application();
config.Routes.Add("Noodles", config.Routes.CreateRoute("{*path}",
new HttpRouteValueDictionary("route"),
constraints: null,
dataTokens: null,
handler: new NoodlesHttpMessageHandler((r) => todoList)
));
server = new HttpSelfHostServer(config);
server.OpenAsync().Wait();
Console.WriteLine("Hit ENTER to exit");
Console.ReadLine();
}
finally
{
if (server != null)
{
server.CloseAsync().Wait();
}
}
}
示例8: SendJsonGetCode
public static HttpStatusCode SendJsonGetCode(string routeTemp, string uri, string json)
{
HttpStatusCode actualHttpCode;
HttpSelfHostConfiguration config
= new HttpSelfHostConfiguration("http://localhost/");
config.Routes.MapHttpRoute(
name: "Default",
routeTemplate: routeTemp
);
using (HttpSelfHostServer server = new HttpSelfHostServer(config))
using (HttpClient client = getJsonClient())
{
server.OpenAsync().Wait();
using (HttpRequestMessage request =
getJsonRequest(HttpMethod.Post, uri, json))
using (HttpResponseMessage response = client.SendAsync(request).Result)
{
actualHttpCode = response.StatusCode;
}
server.CloseAsync().Wait();
}
return actualHttpCode;
}
示例9: Main
public static void Main(string[] args)
{
HttpSelfHostServer server = null;
try
{
var config = new HttpSelfHostConfiguration("http://localhost:3002/")
{
MaxReceivedMessageSize = 1024*1024*1024,
TransferMode = TransferMode.Streamed,
MessageHandlers =
{
new ForwardProxyMessageHandler()
}
};
server = new HttpSelfHostServer(config);
server.OpenAsync().Wait();
Console.WriteLine("Hit ENTER to exit");
Console.ReadLine();
}
finally
{
if (server != null)
{
server.CloseAsync().Wait();
}
}
}
示例10: Body_WithSingletonControllerInstance_Fails
public void Body_WithSingletonControllerInstance_Fails()
{
// Arrange
HttpClient httpClient = new HttpClient();
string baseAddress = "http://localhost";
string requestUri = baseAddress + "/Test";
HttpSelfHostConfiguration configuration = new HttpSelfHostConfiguration(baseAddress);
configuration.Routes.MapHttpRoute("Default", "{controller}", new { controller = "Test" });
configuration.ServiceResolver.SetService(typeof(IHttpControllerFactory), new MySingletonControllerFactory());
HttpSelfHostServer host = new HttpSelfHostServer(configuration);
host.OpenAsync().Wait();
HttpResponseMessage response = null;
try
{
// Act
response = httpClient.GetAsync(requestUri).Result;
response = httpClient.GetAsync(requestUri).Result;
response = httpClient.GetAsync(requestUri).Result;
// Assert
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode);
}
finally
{
if (response != null)
{
response.Dispose();
}
}
host.CloseAsync().Wait();
}
示例11: Get_RequestCorrectCourseId_GetCorrectValues
public void Get_RequestCorrectCourseId_GetCorrectValues()
{
int actualCarId;
string actualZnacka;
string actualModel;
string actualSPZ;
string actualVIN;
int actualPocatecniStavKm;
int actualRokVyroby;
string actualPosledniSTK;
int actualAutoskolaId;
string actualTyp;
int actualNajetoKm;
int actualPrumernaSpotreba;
HttpSelfHostConfiguration config
= new HttpSelfHostConfiguration("http://localhost/");
config.Routes.MapHttpRoute(
name: "Default",
routeTemplate: "{controller}/{id}"
);
using (HttpSelfHostServer server = new HttpSelfHostServer(config))
using (HttpClient client = new HttpClient())
{
server.OpenAsync().Wait();
using (HttpRequestMessage request =
new HttpRequestMessage(HttpMethod.Get, "http://localhost/vozidla/9"))
using (HttpResponseMessage response = client.SendAsync(request).Result)
{
string json = response.Content.ReadAsStringAsync().Result;
dynamic data = JObject.Parse(json);
actualCarId = data.vozidlo_id;
actualZnacka = data.znacka;
actualModel = data.model;
actualSPZ = data.spz;
actualVIN = data.vin;
actualPocatecniStavKm = data.pocatecni_stav_km;
actualRokVyroby = data.rok_vyroby;
actualPosledniSTK = data.posledni_stk;
actualAutoskolaId = data.autoskola_id;
actualTyp = data.vozidlo_typ;
actualNajetoKm = data.pocet_km;
actualPrumernaSpotreba = data.prumerna_spotreba;
}
server.CloseAsync().Wait();
}
Assert.AreEqual(9, actualCarId);
Assert.AreEqual("Škoda",actualZnacka);
Assert.AreEqual("Octavia", actualModel);
Assert.AreEqual("3E8 3853", actualSPZ);
Assert.AreEqual("FG5464RTV5432AF5F", actualVIN);
Assert.AreEqual(8832, actualPocatecniStavKm);
Assert.AreEqual(2007, actualRokVyroby);
Assert.AreEqual(new DateTime(2013, 11, 25).ToString("MM/dd/yyyy HH:mm:ss"), actualPosledniSTK);
Assert.AreEqual(1, actualAutoskolaId);
Assert.AreEqual("osobni", actualTyp);
Assert.AreEqual(8832 + 36, actualNajetoKm);
Assert.AreEqual(6, actualPrumernaSpotreba);
}
示例12: Main
static void Main(string[] args)
{
HttpSelfHostServer server = null;
try
{
// Set up server configuration
HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(_baseAddress);
config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
// Add $format support
config.MessageHandlers.Add(new FormatQueryMessageHandler());
// Add NavigationRoutingConvention2 to support POST, PUT, PATCH and DELETE on navigation property
var conventions = ODataRoutingConventions.CreateDefault();
conventions.Insert(0, new CustomNavigationRoutingConvention());
// Enables OData support by adding an OData route and enabling querying support for OData.
// Action selector and odata media type formatters will be registered in per-controller configuration only
config.Routes.MapODataRoute(
routeName: "OData",
routePrefix: null,
model: ModelBuilder.GetEdmModel(),
pathHandler: new DefaultODataPathHandler(),
routingConventions: conventions);
// Enable queryable support and allow $format query
config.EnableQuerySupport(new QueryableAttribute {
AllowedQueryOptions = AllowedQueryOptions.Supported | AllowedQueryOptions.Format });
// To disable tracing in your application, please comment out or remove the following line of code
// For more information, refer to: http://www.asp.net/web-api
config.EnableSystemDiagnosticsTracing();
config.Filters.Add(new ModelValidationFilterAttribute());
// Create server
server = new HttpSelfHostServer(config);
// Start listening
server.OpenAsync().Wait();
Console.WriteLine("Listening on " + _baseAddress);
}
catch (Exception e)
{
Console.WriteLine("Could not start server: {0}", e.GetBaseException().Message);
}
finally
{
Console.WriteLine("Hit ENTER to exit...");
Console.ReadLine();
if (server != null)
{
// Stop listening
server.CloseAsync().Wait();
}
}
}
示例13: Main
public static void Main(string[] args)
{
HttpSelfHostServer server = null;
try
{
// Set up server configuration
HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(_baseAddress);
config.HostNameComparisonMode = HostNameComparisonMode.Exact;
config.Formatters.JsonFormatter.Indent = true;
config.Formatters.XmlFormatter.Indent = true;
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Create server
server = new HttpSelfHostServer(config);
// Start listening
server.OpenAsync().Wait();
Console.WriteLine("Listening on " + _baseAddress);
Console.WriteLine("*******************************");
Console.WriteLine("POSTing a valid customer");
Console.WriteLine("*******************************");
PostValidCustomer();
Console.WriteLine("*******************************");
Console.WriteLine("POSTing a customer with a missing ID");
Console.WriteLine("*******************************");
PostCustomerMissingID();
Console.WriteLine("*******************************");
Console.WriteLine("POSTing a customer with negative ID and invalid phone number");
Console.WriteLine("*******************************");
PostInvalidCustomerUsingJson();
Console.WriteLine("*******************************");
Console.WriteLine("POSTing a customer with negative ID and invalid phone number using XML");
Console.WriteLine("*******************************");
PostInvalidCustomerUsingXml();
}
catch (Exception e)
{
Console.WriteLine("Could not start server: {0}", e.GetBaseException().Message);
}
finally
{
if (server != null)
{
// Stop listening
server.CloseAsync().Wait();
}
Console.WriteLine("Hit ENTER to exit...");
Console.ReadLine();
}
}
示例14: Main
static void Main(string[] args)
{
HttpSelfHostServer server = null;
try
{
// Configure Server Settings
HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(_baseAddress);
config.Routes.MapHttpRoute(
"API Default", "api/{controller}/{id}",
defaults: new {id = RouteParameter.Optional});
// Create Server
server = new HttpSelfHostServer(config);
//Start Listening
server.OpenAsync().Wait();
Console.WriteLine("Listening on " + _baseAddress);
Console.WriteLine("Press Enter to exit...");
Console.WriteLine();
// Call the web Api and display the result
HttpClient client = new HttpClient();
client.GetStringAsync(_baseAddress).ContinueWith(
getTask =>
{
if (getTask.IsCanceled)
Console.WriteLine("Request was canceled");
else if (getTask.IsFaulted)
Console.WriteLine("Request failed: {0}", getTask.Exception);
else
Console.WriteLine("Client reieved: {0}", getTask.Result);
});
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine("Couln't start Server: {0}", ex.GetBaseException().Message);
Console.WriteLine("Press Enter to exit..");
Console.ReadLine();
}
finally
{
if (server != null)
{
// Stop Listening
server.CloseAsync().Wait();
}
}
}
示例15: Main
static void Main(string[] args)
{
HttpSelfHostServer server = null;
try
{
// Create configuration
var config = new HttpSelfHostConfiguration(_baseAddress);
config.HostNameComparisonMode = HostNameComparisonMode.Exact;
// Turn on streaming in selfhost for both requests and responses.
// if you do this in ASP.NET then please see this blog from @filip_woj for details
// on how to turn off buffering in ASP.NET:
// http://www.strathweb.com/2012/09/dealing-with-large-files-in-asp-net-web-api/
config.TransferMode = TransferMode.Streamed;
// Set max received size to 10G
config.MaxReceivedMessageSize = 10L * 1024 * 1024 * 1024;
// Set receive and send timeout to 20 mins
config.ReceiveTimeout = TimeSpan.FromMinutes(20);
config.SendTimeout = TimeSpan.FromMinutes(20);
// Add a route
config.Routes.MapHttpRoute(
name: "default",
routeTemplate: "api/{controller}/{id}",
defaults: new { controller = "Home", id = RouteParameter.Optional });
// Create server
server = new HttpSelfHostServer(config);
// Start server
server.OpenAsync().Wait();
Console.WriteLine("Server listening at {0}", _baseAddress);
Console.WriteLine("Hit ENTER to exit");
Console.ReadLine();
}
catch (Exception e)
{
Console.WriteLine("Could not start server: {0}", e.GetBaseException().Message);
Console.WriteLine("Hit ENTER to exit...");
Console.ReadLine();
}
finally
{
if (server != null)
{
// Close server
server.CloseAsync().Wait();
}
}
}