本文整理汇总了C#中System.Web.Http.SelfHost.HttpSelfHostServer类的典型用法代码示例。如果您正苦于以下问题:C# HttpSelfHostServer类的具体用法?C# HttpSelfHostServer怎么用?C# HttpSelfHostServer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
HttpSelfHostServer类属于System.Web.Http.SelfHost命名空间,在下文中一共展示了HttpSelfHostServer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Main
static void Main(string[] args)
{
var config = new HttpSelfHostConfiguration("http://localhost:8999");
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// using asp.net like hosting
// HttpSelfHostServer is using a different constructor compared to the previous project (SelfHost1)
var server = new HttpSelfHostServer(config);
var task = server.OpenAsync();
task.Wait();
Console.WriteLine("Server is up and running");
Console.WriteLine("Hit enter to call server with client");
Console.ReadLine();
// HttpSelfHostServer, derives from HttpMessageHandler => multiple level of inheritance
var client = new HttpClient(server);
client.GetAsync("http://localhost:8999/api/my").ContinueWith(t =>
{
var result = t.Result;
result.Content.ReadAsStringAsync()
.ContinueWith(rt =>
{
Console.WriteLine("client got response" + rt.Result);
});
});
Console.ReadLine();
}
示例2: Main
static void Main(string[] args)
{
// run as administrator: netsh http add urlacl url=http://+:56473/ user=machine\username
// http://www.asp.net/web-api/overview/older-versions/self-host-a-web-api
var config = new HttpSelfHostConfiguration("http://localhost:56473");
config.Routes.MapHttpRoute("Default", "{controller}.json");
config.Formatters.Remove(config.Formatters.XmlFormatter);
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(
new Newtonsoft.Json.Converters.StringEnumConverter());
config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(
new Newtonsoft.Json.Converters.IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm" });
using (HttpSelfHostServer server = new HttpSelfHostServer(config))
{
server.OpenAsync().Wait();
Console.WriteLine("Press Enter to quit...");
Console.ReadLine();
}
}
示例3: CreateHttpClient
public static HttpClient CreateHttpClient()
{
var baseAddress = new Uri("http://localhost:8080");
var config = new HttpSelfHostConfiguration(baseAddress);
// ?
Setup.Configure(config);
var server = new HttpSelfHostServer(config);
var client = new HttpClient(server); // <--- MAGIC!
try
{
client.BaseAddress = baseAddress;
return client;
}
catch
{
client.Dispose();
throw;
}
}
示例4: Main
static void Main(string[] args)
{
var cfg = new HttpSelfHostConfiguration("http://localhost:1337");
cfg.MaxReceivedMessageSize = 16L * 1024 * 1024 * 1024;
cfg.TransferMode = TransferMode.StreamedRequest;
cfg.ReceiveTimeout = TimeSpan.FromMinutes(20);
cfg.Routes.MapHttpRoute(
"API Default", "api/{controller}/{id}",
new { id = RouteParameter.Optional });
cfg.Routes.MapHttpRoute(
"Default", "{*res}",
new { controller = "StaticFile", res = RouteParameter.Optional });
var db = new EmbeddableDocumentStore { DataDirectory = new FileInfo("db/").DirectoryName };
db.Initialize();
cfg.Filters.Add(new RavenDbApiAttribute(db));
using (HttpSelfHostServer server = new HttpSelfHostServer(cfg))
{
Console.WriteLine("Initializing server.");
server.OpenAsync().Wait();
Console.WriteLine("Server ready at: " + cfg.BaseAddress);
Console.WriteLine("Press Enter to quit.");
Console.ReadLine();
}
}
示例5: Main
static void Main(string[] args)
{
//var config = new HttpSelfHostConfiguration("http://localhost:8999");
var config = new MyConfig("http://localhost:8999");
config.Routes.MapHttpRoute(
"DefaultRoute", "{controller}/{id}",
new { id = RouteParameter.Optional });
//custom message processing
//var server = new HttpSelfHostServer(config,
// new MyNewSimpleMessagehandler());
//controller message processing
var server = new HttpSelfHostServer(config,
new MyNewSimpleMessagehandler());
server.OpenAsync();
//trick, calls server just created to confirm it works
var client = new HttpClient(server);
client.GetAsync("http://localhost:8999/simple")
.ContinueWith((t) =>
{
var result = t.Result;
result.Content.ReadAsStringAsync()
.ContinueWith((rt) => {
Console.WriteLine("Client got " + rt.Result);
});
});
//
Console.WriteLine("opening web api selfhost ");
Console.ReadKey();
}
示例6: Start
public void Start()
{
selfHostServer = new HttpSelfHostServer(httpSelfHostConfiguration);
selfHostServer.OpenAsync();
Logger.Info("Started management app host");
}
示例7: Given_command_server_runnig
public void Given_command_server_runnig()
{
var config = ZazServer.ConfigureAsSelfHosted(URL, new ServerConfiguration
{
Registry = new FooCommandRegistry(),
Broker = new DelegatingCommandBroker((cmd, ctx) =>
{
throw new InvalidOperationException("Server failed...");
// return Task.Factory.StartNew(() => { });
})
});
using (var host = new HttpSelfHostServer(config))
{
host.OpenAsync().Wait();
// Client side
var bus = new ZazClient(URL);
try
{
bus.PostAsync(new FooCommand
{
Message = "Hello world"
}).Wait();
}
catch (Exception ex)
{
_resultEx = ex;
}
}
}
示例8: OpenConfiguredServiceHost
public static HttpSelfHostServer OpenConfiguredServiceHost(this CommandsController @this, string url)
{
var config = ZazServer.ConfigureAsSelfHosted(url);
var host = new HttpSelfHostServer(config);
host.OpenAsync().Wait();
return host;
}
示例9: 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();
}
示例10: SampleService
public SampleService(bool throwOnStart, bool throwOnStop, bool throwUnhandled, Uri address)
{
_throwOnStart = throwOnStart;
_throwOnStop = throwOnStop;
_throwUnhandled = throwUnhandled;
if (!EventLog.SourceExists(EventSource))
{
EventLog.CreateEventSource(EventSource, "Application");
}
EventLog.WriteEntry(EventSource,
String.Format("Creating server at {0}",
address.ToString()));
_config = new HttpSelfHostConfiguration(address);
_config.Routes.MapHttpRoute("DefaultApi",
"api/{controller}/{id}",
new { id = RouteParameter.Optional }
);
_config.Routes.MapHttpRoute(
"Default", "{controller}/{action}",
new { controller = "Home", action = "Index", date = RouteParameter.Optional});
const string viewPathTemplate = "SampleTopshelfService.Views.{0}";
var templateConfig = new TemplateServiceConfiguration();
templateConfig.Resolver = new DelegateTemplateResolver(name =>
{
string resourcePath = string.Format(viewPathTemplate, name);
var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourcePath);
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
});
Razor.SetTemplateService(new TemplateService(templateConfig));
_server = new HttpSelfHostServer(_config);
}
示例11: 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();
}
示例12: Main
/// <summary>
/// The program main method
/// </summary>
/// <param name="args">The program arguments</param>
private static void Main(string[] args)
{
var config = new HttpSelfHostConfiguration(ServiceAddress);
config.MapHttpAttributeRoutes();
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
using (var server = new HttpSelfHostServer(config)) {
try {
server.OpenAsync().Wait();
Console.WriteLine("Service running on " + ServiceAddress + ". Press enter to quit.");
Console.ReadLine();
}
catch (Exception e) {
if (!IsAdministrator()) {
Console.WriteLine("Please restart as admin.");
Debug.WriteLine("Restart Visual Studio as admin");
}
else {
Console.WriteLine("Server failed to start.");
}
Console.ReadLine();
}
}
}
示例13: WebApiTest
public WebApiTest()
{
IOExtensions.DeleteDirectory("Test");
NonAdminHttp.EnsureCanListenToWhenInNonAdminContext(19079);
Task.Factory.StartNew(() => // initialize in MTA thread
{
config = new HttpSelfHostConfiguration(Url)
{
MaxReceivedMessageSize = Int64.MaxValue,
TransferMode = TransferMode.Streamed
};
var configuration = new InMemoryConfiguration();
configuration.Initialize();
configuration.DataDirectory = "~/Test";
ravenFileSystem = new RavenFileSystem(configuration);
ravenFileSystem.Start(config);
})
.Wait();
server = new HttpSelfHostServer(config);
server.OpenAsync().Wait();
WebClient = new WebClient
{
BaseAddress = Url
};
}
示例14: Init
public override void Init()
{
var actions = new HttpMethodCollection();
foreach (var action in RequestReceived)
{
actions.RegisterMethod(action.Metadata, action.Value);
}
var config = new HttpSelfHostConfiguration(BASE_URL_HTTP)
{
DependencyResolver = new DependencyResolver(actions, Logger)
};
config.Routes.MapHttpRoute(
"API Default", "api/{pluginName}/{methodName}/{callback}",
new
{
controller = "Common",
action = "Get",
callback = RouteParameter.Optional
})
.DataTokens["Namespaces"] = new[] {"ThinkingHome.Plugins.Listener.Api"};
server = new HttpSelfHostServer(config);
}
示例15: Main
public static void Main(string[] args)
{
var config = new HttpSelfHostConfiguration("http://127.0.0.1:3001");
config.MapHttpAttributeRoutes();
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "ReportsApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
using (HttpSelfHostServer server = new HttpSelfHostServer(config))
{
server.OpenAsync().Wait();
Console.WriteLine("Press Enter to quit.");
Console.ReadLine();
}
}