本文整理汇总了C#中System.Web.Http.SelfHost.HttpSelfHostConfiguration.EnableCors方法的典型用法代码示例。如果您正苦于以下问题:C# HttpSelfHostConfiguration.EnableCors方法的具体用法?C# HttpSelfHostConfiguration.EnableCors怎么用?C# HttpSelfHostConfiguration.EnableCors使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Web.Http.SelfHost.HttpSelfHostConfiguration
的用法示例。
在下文中一共展示了HttpSelfHostConfiguration.EnableCors方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: 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();
}
}
示例2: 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;
}
示例3: 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();
}
}
}
示例4: 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);
}
示例5: StartServer
static void StartServer()
{
var config = new HttpSelfHostConfiguration(ServiceAddress);
config.Routes.MapHttpRoute(
"API Default", "{controller}/{action}/{id}",
new
{
id = RouteParameter.Optional,
controller = new WinampController()
});
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
var server = new HttpSelfHostServer(config);
server.OpenAsync().Wait();
}
示例6: Main
static void Main(string[] args)
{
HttpSelfHostServer server = null;
try
{
// Set up server configuration
HttpSelfHostConfiguration config = new HttpSelfHostConfiguration(_baseAddress);
config.EnableCors();
config.Routes.MapHttpRoute(
name: "MoveLeft",
routeTemplate: "api/{controller}/{action}"
);
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);
// Call the web API and display the result
HttpClient client = new HttpClient();
client.GetStringAsync(_address).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 received: {0}", getTask.Result);
}
});
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();
}
}
}
示例7: StartHttp
private async Task StartHttp()
{
var baseAddress = new Uri($"http://localhost:{PortSetting}/");
try
{
// Set up server configuration
var config = new HttpSelfHostConfiguration(baseAddress);
// config.Services.Replace(typeof(ITraceWriter), new SimpleTracer());
//Add our way too simple Authentication
config.Filters.Add(new ZvsAuthenticatioFilter(this));
// Web API routes
config.MapHttpAttributeRoutes();
var resolver = new WebApi2PluginDependencyResolver(this);
config.DependencyResolver = resolver;
config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
//config.Routes.MapHttpRoute(
// name: "DefaultApi",
// routeTemplate: "api/{controller}/{id}",
// defaults: new { id = RouteParameter.Optional }
//);
var builder = new ODataConventionModelBuilder();
var scheduledTaskType = builder.EntityType<ScheduledTask>();
scheduledTaskType.Ignore(t => t.StartTime);
scheduledTaskType.Property(t => t.StartTimeOffset).Name = "StartTime";
var deviceValueHistoryTaskType = builder.EntityType<DeviceValueHistory>();
deviceValueHistoryTaskType.Ignore(t => t.DateTime);
deviceValueHistoryTaskType.Property(t => t.DateTimeOffset).Name = "DateTime";
var logEntryType = builder.EntityType<LogEntry>();
logEntryType.Ignore(t => t.Datetime);
logEntryType.Property(t => t.DateTimeOffset).Name = "Datetime";
builder.EntitySet<Command>("Commands");
var cExecute = builder.EntityType<Command>().Action("Execute");
cExecute.Parameter<string>("Argument");
cExecute.Parameter<string>("Argument2");
builder.EntitySet<BuiltinCommand>("BuiltinCommands");
builder.EntitySet<Device>("Devices");
builder.EntitySet<DeviceCommand>("DeviceCommands");
builder.EntitySet<DeviceTypeCommand>("DeviceTypeCommands");
builder.EntitySet<DeviceValueTrigger>("DeviceValueTriggers");
builder.EntitySet<DeviceValue>("DeviceValues");
builder.EntitySet<DeviceValueHistory>("DeviceValueHistories");
builder.EntitySet<Group>("Groups");
builder.EntitySet<Scene>("Scenes");
builder.EntitySet<SceneStoredCommand>("SceneStoredCommands");
builder.EntitySet<ScheduledTask>("ScheduledTasks");
builder.EntitySet<LogEntry>("LogEntries");
builder.Namespace = "Actions";
config.MapODataServiceRoute("ODataRoute", "odata4", builder.GetEdmModel());
//config.MapODataServiceRoute(
//routeName: "ODataRoute",
//routePrefix: null,
//model: builder.GetEdmModel());
// Create server
HttpSelfHostServer = new HttpSelfHostServer(config);
// Start listening
await HttpSelfHostServer.OpenAsync();
}
catch (Exception e)
{
Console.WriteLine("Could not start server: {0}", e.GetBaseException().Message);
}
await Log.ReportInfoFormatAsync(CancellationToken, "WebApi2 Server Online on port {0} {1} SSL", baseAddress, UseSslSetting ? "using" : "not using");
}
示例8: ConfigureServer
static HttpSelfHostServer ConfigureServer(string serverUrl)
{
// set up the server side
var config = new HttpSelfHostConfiguration(serverUrl);
// Attribute routing
config.MapHttpAttributeRoutes();
// Convention-based routing
config.Routes.MapHttpRoute(
"API Default", "api/{controller}/{id}",
new { id = RouteParameter.Optional });
// set the default WebAPI format to JSON
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
// enable Cross Origin Resource Sharing
config.EnableCors();
return new HttpSelfHostServer(config);
}