本文整理汇总了C#中System.Web.Http.SelfHost.HttpSelfHostConfiguration类的典型用法代码示例。如果您正苦于以下问题:C# HttpSelfHostConfiguration类的具体用法?C# HttpSelfHostConfiguration怎么用?C# HttpSelfHostConfiguration使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
HttpSelfHostConfiguration类属于System.Web.Http.SelfHost命名空间,在下文中一共展示了HttpSelfHostConfiguration类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetHttpConfiguration
private HttpSelfHostConfiguration GetHttpConfiguration()
{
var config = new HttpSelfHostConfiguration(BaseAddress);
config.Routes.MapHttpRoute("Locator", "api.xml", new {controller = "ApiXml"});
config.Routes.MapHttpRoute("Api", "api.asp", new {controller = "ApiAsp"});
return config;
}
示例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: Configure
private static void Configure(HttpSelfHostConfiguration config)
{
config.Routes.MapHttpRoute("Default Route", "api/{controller}", new { controller = "Home" });
config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
config.Filters.Add(new ServiceControlErrorFilter());
config.Filters.Add(new VersionInformationFilter());
}
示例5: 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();
}
}
示例6: Main
static void Main(string[] args)
{
// classic
var config = new HttpSelfHostConfiguration("http://localhost:18081");
// HTTPS
//var config = new HttpsSelfHostConfiguration("http://localhost:18081");
// NTLM
//var config = new NtlmHttpSelfHostConfiguration("http://localhost:18081");
// BASIC AUTHENTICATION
//var config = new BasicAuthenticationSelfHostConfiguration("http://localhost:18081",
// (un, pwd) => un == "johndoe" && pwd == "123456");
config.Routes.MapHttpRoute(
"API Default", "api/{controller}/{id}",
new { id = RouteParameter.Optional });
using (var server = new HttpSelfHostServer(config))
{
server.OpenAsync().Wait();
Console.WriteLine("Press Enter to quit.");
Console.ReadLine();
}
}
示例7: SendJsonGetJson
public static JObject SendJsonGetJson(HttpMethod method, string routeTemp, string uri, string json)
{
JObject result;
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(method, uri, json))
using (HttpResponseMessage response = client.SendAsync(request).Result)
{
string responseJson = response.Content.ReadAsStringAsync().Result;
result = JObject.Parse(responseJson);
}
server.CloseAsync().Wait();
}
return result;
}
示例8: 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
};
}
示例9: 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();
}
}
}
示例10: SetUp
public void SetUp()
{
var config = new HttpSelfHostConfiguration(URL);
ZazServer.Configure(config, Prefix1, new ServerConfiguration
{
Registry = new FooCommandRegistry(),
Broker = new DelegatingCommandBroker((o, context) =>
{
_api1Command = (FooCommand)o;
return Task.Factory.StartNew(() => { });
}),
});
ZazServer.Configure(config, Prefix2, new ServerConfiguration
{
Registry = new FooCommandRegistry(),
Broker = new DelegatingCommandBroker((o, context) =>
{
_api2Command = (FooCommand)o;
return Task.Factory.StartNew(() => { });
}),
});
_host = new HttpSelfHostServer(config);
_host.OpenAsync().Wait();
}
开发者ID:JustApplications,项目名称:zaz,代码行数:26,代码来源:When_configuring_multiple_endpoints_within_1_webhost.cs
示例11: 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();
}
示例12: OnStart
protected override void OnStart(string[] args)
{
Uri baseAddress = new Uri("http://" + ConfigurationManager.AppSettings["server"] + GetPort());
HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(baseAddress)
{
HostNameComparisonMode = HostNameComparisonMode.Exact
};
string origins = ConfigurationManager.AppSettings["corsItems"];
if (string.IsNullOrEmpty(origins))
{
origins = "*";
}
config.EnableCors(new EnableCorsAttribute(origins, "*", "*"));
var formatters = GlobalConfiguration.Configuration.Formatters;
formatters.Remove(formatters.XmlFormatter);
WebApiConfig.Register(config);
config.MapHttpAttributeRoutes();
config.EnsureInitialized();
_server = new HttpSelfHostServer(config);
// Start listening
_server.OpenAsync().Wait();
System.Console.WriteLine("Listening on " + baseAddress);
}
示例13: 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();
}
}
}
示例14: 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();
}
}
示例15: GetSettings
private static HttpSelfHostConfiguration GetSettings()
{
var localhostAddress = ConfigurationManager.AppSettings[SettingsHelper.KEY_LOCALHOST_ADDRESS];
var serverConfiguration = new HttpSelfHostConfiguration(localhostAddress);
serverConfiguration.Filters
.Add(new ExceptionResponseFilterAttribute());
serverConfiguration.Routes
.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{parameters}",
defaults: new
{
parameters = RouteParameter.Optional
}
);
var xmlFormatter = serverConfiguration.Formatters.OfType<XmlMediaTypeFormatter>().First();
var jsonFormatter = serverConfiguration.Formatters.OfType<JsonMediaTypeFormatter>().First();
var cors = new EnableCorsAttribute("*", "GET", "GET");
serverConfiguration.EnableCors(cors);
serverConfiguration.Formatters.Remove(xmlFormatter);
jsonFormatter.SerializerSettings = new JsonSerializerSettings() { ContractResolver = new CamelCasePropertyNamesContractResolver() };
return serverConfiguration;
}