本文整理汇总了C#中System.ServiceModel.WebHttpBinding类的典型用法代码示例。如果您正苦于以下问题:C# WebHttpBinding类的具体用法?C# WebHttpBinding怎么用?C# WebHttpBinding使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
WebHttpBinding类属于System.ServiceModel命名空间,在下文中一共展示了WebHttpBinding类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: TestDataService
public TestDataService(string baseUrl, Type serviceType)
{
for (var i = 0; i < 100; i++)
{
var hostId = Interlocked.Increment(ref _lastHostId);
this._serviceUri = new Uri(baseUrl + hostId);
this._host = new DataServiceHost(serviceType, new Uri[] { this._serviceUri });
var binding = new WebHttpBinding { MaxReceivedMessageSize = Int32.MaxValue };
_host.AddServiceEndpoint(typeof(System.Data.Services.IRequestHandler), binding, _serviceUri);
//var endpoing = new ServiceEndPoint
//this._host.Description.Endpoints[0].Binding
//this._host.AddServiceEndpoint(serviceType, binding, this._serviceUri);
try
{
this._host.Open();
break;
}
catch (Exception)
{
this._host.Abort();
this._host = null;
}
}
if (this._host == null)
{
throw new InvalidOperationException("Could not open a service even after 100 tries.");
}
}
示例2: Main
static void Main(string[] args)
{
Console.WriteLine("Инициализация...");
var properties = ConnectionSettings.Default;
var baseUrl = new Uri(properties.host);
var contractType = typeof (IRestBridgeContract);
var binding = new WebHttpBinding(WebHttpSecurityMode.None);
binding.ContentTypeMapper = new JsonContentTypeMapper();
var server = new ServiceHost(typeof (CastDriverBridgeEmulatorImpl));
var endPoint = server.AddServiceEndpoint(contractType, binding, baseUrl);
var behavior = new WebHttpBehavior();
behavior.FaultExceptionEnabled = false;
behavior.HelpEnabled = true;
behavior.DefaultOutgoingRequestFormat = WebMessageFormat.Json;
behavior.DefaultOutgoingResponseFormat = WebMessageFormat.Json;
endPoint.Behaviors.Add(behavior);
Console.WriteLine("Инициализация завершена.");
Console.WriteLine("Запуск сервера...");
server.Open();
Console.WriteLine("Сервер запущен. Адрес сервера: {0}\nДля остановки нажмите Enter.", properties.host);
Console.ReadLine();
Console.WriteLine("Остановка сервера...");
server.Close();
Console.WriteLine("Сервер остановлен.");
Console.ReadLine();
}
示例3: Main
public static void Main ()
{
var url = "http://localhost:8080";
var host = new MyHostFactory ().CreateServiceHost (typeof (HogeService));
var binding = new WebHttpBinding ();
host.AddServiceEndpoint (typeof (IHogeService), binding, url);
host.Open ();
//Console.WriteLine ("js:");
//Console.WriteLine (new WebClient ()
// .DownloadString (url + "/js"));
Console.WriteLine ("jsdebug:");
Console.WriteLine (new WebClient ()
.DownloadString (url + "/jsdebug"));
Console.WriteLine (new WebClient ()
.DownloadString (url + "/Join?s1=foo&s2=bar"));
Console.WriteLine (new WebClient ()
.DownloadString (url + "/ToComplex?real=3&unreal=4"));
foreach (ChannelDispatcher cd in host.ChannelDispatchers) {
Console.WriteLine ("BindingName: " + cd.BindingName);
Console.WriteLine (cd.Listener.Uri);
foreach (var o in cd.Endpoints [0].DispatchRuntime.Operations)
Console.WriteLine ("OP: {0} {1}", o.Name, o.Action);
}
Console.WriteLine ("Type [CR] to close ...");
Console.ReadLine ();
host.Close ();
}
示例4: Main
static void Main(string[] args)
{
Uri baseAddress = new Uri("http://localhost:8000/");
ServiceHost selfHost = new WebServiceHost(typeof(MonitorService), baseAddress);
try
{
// Step 3 Add a service endpoint.
var t = new WebHttpBinding();
selfHost.AddServiceEndpoint(typeof(IMonitorService), t, "test");
WebHttpBehavior whb = new WebHttpBehavior();
// Step 4 Enable metadata exchange.
ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
smb.HttpGetEnabled = true;
selfHost.Description.Behaviors.Add(smb);
// Step 5 Start the service.
selfHost.Open();
Console.WriteLine("The service is ready.");
Console.WriteLine("Press <ENTER> to terminate service.");
Console.WriteLine();
Console.ReadLine();
// Close the ServiceHostBase to shutdown the service.
selfHost.Close();
}
catch (CommunicationException ce)
{
Console.WriteLine("An exception occurred: {0}", ce.Message);
selfHost.Abort();
}
}
示例5: CreateServiceHost
public static ServiceHost CreateServiceHost()
{
/*var uri = new Uri("http://localhost:8686/hello");
var host = new ServiceHost(typeof(HelloService), uri);
var binding = new BasicHttpBinding();
host.AddServiceEndpoint(typeof(IHelloService), binding, uri);
var metadata = new ServiceMetadataBehavior();
metadata.HttpGetEnabled = true;
metadata.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
host.Description.Behaviors.Add(metadata);
return host;*/
var baseAddress = new Uri("http://localhost:8686/blog");
// var baseAddress = new UriBuilder(Uri.UriSchemeHttp, Environment.MachineName, -1, "/blogdemo/").Uri;
var serviceHost = new ServiceHost(typeof(BloggerAPI), baseAddress);
var epXmlRpc = serviceHost.AddServiceEndpoint(typeof(IBloggerAPI), new WebHttpBinding(WebHttpSecurityMode.None), baseAddress);
epXmlRpc.Behaviors.Add(new XmlRpcEndpointBehavior());
var webBinding = new WebHttpBinding(WebHttpSecurityMode.None);
var epFeed = serviceHost.AddServiceEndpoint(typeof(IFeed), webBinding, new Uri(baseAddress, "./feed"));
epFeed.Behaviors.Add(new WebHttpBehavior());
return serviceHost;
}
示例6: Main
static void Main(string[] args)
{
ItemCounter counter = new ItemCounter();
using (WebServiceHost host = new WebServiceHost(new StreamingFeedService(counter), new Uri("http://localhost:8000/Service")))
{
WebHttpBinding binding = new WebHttpBinding();
binding.TransferMode = TransferMode.StreamedResponse;
host.AddServiceEndpoint(typeof(IStreamingFeedService), binding, "Feeds");
host.Open();
XmlReader reader = XmlReader.Create("http://localhost:8000/Service/Feeds/StreamedFeed");
StreamedAtom10FeedFormatter formatter = new StreamedAtom10FeedFormatter(counter);
Console.WriteLine("Reading stream from server");
formatter.ReadFrom(reader);
SyndicationFeed feed = formatter.Feed;
foreach (SyndicationItem item in feed.Items)
{
//This sample is implemented such that the server will generate an infinite stream of items;
//it only stops after the client reads 10 items
counter.Increment();
}
Console.WriteLine("CLIENT: read total of {0} items", counter.GetCount());
Console.WriteLine("Press any key to terminate");
Console.ReadLine();
}
}
示例7: SafeServiceHost
public SafeServiceHost(VLogger logger, Type contractType, SafeServicePolicyDecider consumer, string webAddressSuffix, params string[] addresses)
{
object instance = consumer;
this.policyDecider = consumer;
this.logger = logger;
List<Uri> addressList = new List<Uri>();
foreach (String address in addresses)
{
addressList.Add(new Uri(address+webAddressSuffix));
}
serviceHost = new ServiceHost(instance, addressList.ToArray());
serviceHost.Authentication.ServiceAuthenticationManager = new SafeServiceAuthenticationManager();
serviceHost.Authorization.ServiceAuthorizationManager = new SafeServiceAuthorizationManager(consumer, this);
foreach (string address in addresses)
{
var contract = ContractDescription.GetContract(contractType);
var webBinding = new WebHttpBinding();
var webEndPoint = new ServiceEndpoint(contract, webBinding, new EndpointAddress(address+webAddressSuffix));
webEndPoint.EndpointBehaviors.Add(new WebHttpBehavior());
serviceHost.AddServiceEndpoint(webEndPoint);
}
}
示例8: FilesWinService
public FilesWinService(ILog log, IConfig config, IFirewallService firewallService)
: base(log, true)
{
this.config = config;
this.firewallService = firewallService;
Uri baseAddress = config.FilesServiceUri;
var webHttpBinding = new WebHttpBinding();
webHttpBinding.Security.Mode = WebHttpSecurityMode.TransportCredentialOnly;
webHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
var serviceHost = new IocServiceHost(typeof(FilesService), baseAddress);
base.serviceHost = serviceHost;
ServiceEndpoint endpoint = serviceHost.AddServiceEndpoint(typeof(IFilesService), webHttpBinding, baseAddress);
endpoint.Behaviors.Add(new WebHttpBehavior());
ServiceCredential filesCredentials = config.FilesCredentials;
#if DEBUG
log.Debug("FilesWinService baseAddress: {0} credentials: {1}:{2}",
baseAddress, filesCredentials.Username, filesCredentials.Password);
#endif
serviceHost.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = new CustomUserNamePasswordValidator(filesCredentials);
serviceHost.Credentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom;
}
示例9: Initialize
/// <summary>
/// Initializes and hosts all services.
/// </summary>
public void Initialize()
{
// Host the public web service
if (_settingWSIsEnabled.Value)
{
string address = string.Format("http://localhost:{0}/AlarmWorkflow/AlarmWorkflowService", _settingWSPort.Value);
Binding binding = new WebHttpBinding()
{
HostNameComparisonMode = System.ServiceModel.HostNameComparisonMode.WeakWildcard,
MaxReceivedMessageSize = int.MaxValue,
ReaderQuotas = XmlDictionaryReaderQuotas.Max,
};
HostService(address, binding, typeof(IAlarmWorkflowService), new AlarmWorkflowService(_parent));
}
// Host the service used for local-machine communication between service and clients (such as the Windows/Linux UI)
{
string address = "net.pipe://localhost/alarmworkflow/service";
NetNamedPipeBinding binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.Transport)
{
MaxReceivedMessageSize = int.MaxValue,
ReaderQuotas = XmlDictionaryReaderQuotas.Max,
};
HostService(address, binding, typeof(IAlarmWorkflowServiceInternal), new AlarmWorkflowServiceInternal(_parent));
}
}
示例10: Main
static void Main(string[] args)
{
WebServiceHost webServiceHost = new WebServiceHost(typeof(PartyService.Service));
WebHttpBinding serviceBinding = new WebHttpBinding(WebHttpSecurityMode.TransportCredentialOnly);
serviceBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
ServiceEndpoint ep = webServiceHost.AddServiceEndpoint(
typeof(PartyService.IService),
serviceBinding,
"http://localhost:8000/service");
ep.Behaviors.Add(new PartyService.ProcessorBehaviour());
WebHttpBinding staticBinding = new WebHttpBinding(WebHttpSecurityMode.None);
ServiceEndpoint sep = webServiceHost.AddServiceEndpoint(
typeof(PartyService.IStaticItemService),
new WebHttpBinding(),
"http://localhost:8000");
webServiceHost.Credentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom;
webServiceHost.Credentials.UserNameAuthentication.CustomUserNamePasswordValidator = new PartyService.Validator();
webServiceHost.Description.Behaviors.Find<ServiceDebugBehavior>().IncludeExceptionDetailInFaults = true;
webServiceHost.Open();
Console.WriteLine("Service is running - press enter to quit");
Console.ReadLine();
webServiceHost.Close();
Console.WriteLine("Service stopped");
}
示例11: Main
static void Main(string[] args)
{
string baseAddress = "http://" + Environment.MachineName + ":8000/Service";
ServiceHost host = new ServiceHost(typeof(Service), new Uri(baseAddress));
host.AddServiceEndpoint(typeof(ITestService), new BasicHttpBinding(), "soap");
WebHttpBinding webBinding = new WebHttpBinding();
webBinding.ContentTypeMapper = new MyRawMapper();
host.AddServiceEndpoint(typeof(ITestService), webBinding, "json").Behaviors.Add(new NewtonsoftJsonBehavior());
Console.WriteLine("Opening the host");
host.Open();
ChannelFactory<ITestService> factory = new ChannelFactory<ITestService>(new BasicHttpBinding(), new EndpointAddress(baseAddress + "/soap"));
ITestService proxy = factory.CreateChannel();
Console.WriteLine(proxy.GetPerson());
SendRequest(baseAddress + "/json/GetPerson", "GET", null, null);
SendRequest(baseAddress + "/json/EchoPet", "POST", "application/json", "{\"Name\":\"Fido\",\"Color\":\"Black and white\",\"Markings\":\"None\",\"Id\":1}");
SendRequest(baseAddress + "/json/Add", "POST", "application/json", "{\"x\":111,\"z\":null,\"w\":[1,2],\"v\":{\"a\":1},\"y\":222}");
Console.WriteLine("Now using the client formatter");
ChannelFactory<ITestService> newFactory = new ChannelFactory<ITestService>(webBinding, new EndpointAddress(baseAddress + "/json"));
newFactory.Endpoint.Behaviors.Add(new NewtonsoftJsonBehavior());
ITestService newProxy = newFactory.CreateChannel();
Console.WriteLine(newProxy.Add(444, 555));
Console.WriteLine(newProxy.EchoPet(new Pet { Color = "gold", Id = 2, Markings = "Collie", Name = "Lassie" }));
Console.WriteLine(newProxy.GetPerson());
Console.WriteLine("Press ENTER to close");
Console.ReadLine();
host.Close();
Console.WriteLine("Host closed");
}
示例12: RunInterface
/// <summary>
/// OSA Plugin Interface - called on start up to allow plugin to do any tasks it needs
/// </summary>
/// <param name="pluginName">The name of the plugin from the system</param>
public override void RunInterface(string pluginName)
{
pName = pluginName;
try
{
this.Log.Info("Starting Rest Interface");
bool showHelp = bool.Parse(OSAEObjectPropertyManager.GetObjectPropertyValue(pName, "Show Help").Value);
serviceHost = new WebServiceHost(typeof(OSAERest.api), new Uri("http://localhost:8732/api"));
WebHttpBinding binding = new WebHttpBinding(WebHttpSecurityMode.None);
binding.CrossDomainScriptAccessEnabled = true;
var endpoint = serviceHost.AddServiceEndpoint(typeof(IRestService), binding, "");
ServiceDebugBehavior sdb = serviceHost.Description.Behaviors.Find<ServiceDebugBehavior>();
sdb.HttpHelpPageEnabled = false;
if (showHelp)
{
serviceHost.Description.Endpoints[0].Behaviors.Add(new WebHttpBehavior { HelpEnabled = true });
}
this.Log.Info("Starting Rest Interface");
serviceHost.Open();
}
catch (Exception ex)
{
this.Log.Error("Error starting RESTful web service", ex);
}
}
示例13: DifferentWriteEncodingsTest
public void DifferentWriteEncodingsTest()
{
Encoding[] validEncodings = new Encoding[]
{
Encoding.UTF8,
Encoding.Unicode,
Encoding.BigEndianUnicode,
};
string[] charsetValues = new string[] { "utf-8", "utf-16LE", "utf-16BE" };
for (int i = 0; i < validEncodings.Length; i++)
{
Encoding encoding = validEncodings[i];
WebHttpBinding binding = new WebHttpBinding();
binding.WriteEncoding = encoding;
WebHttpBehavior3 behavior = new WebHttpBehavior3();
string baseAddress = TestService.BaseAddress;
using (ServiceHost host = new ServiceHost(typeof(TestService), new Uri(baseAddress)))
{
host.AddServiceEndpoint(typeof(ITestService), binding, "").Behaviors.Add(behavior);
host.Open();
HttpWebRequest request = WebHttpBehavior3Test.CreateRequest("GET", baseAddress + "/EchoGet?a=1", null, null, null);
HttpWebResponse resp = (HttpWebResponse)request.GetResponse();
Assert.AreEqual(HttpStatusCode.OK, resp.StatusCode);
Assert.AreEqual("application/json; charset=" + charsetValues[i], resp.ContentType);
Stream respStream = resp.GetResponseStream();
string responseBody = new StreamReader(respStream, encoding).ReadToEnd();
Assert.AreEqual("{\"a\":\"1\"}", responseBody);
}
}
}
示例14: OnShare
public void OnShare(object sender, EventArgs e)
{
bool putFileNameInUri = this.checkBoxPutFileNameInUrl.Checked;
int hoursToShare = int.Parse(this.dropDownHoursToShare.SelectedValue);
var listItem = GetListItem();
if (listItem == null) return;
try
{
var binding = new WebHttpBinding();
var endpoint = new EndpointAddress(GetServiceUrl());
var channelFactory = new ChannelFactory<Services.IAzureSharer>(binding, endpoint);
channelFactory.Endpoint.Behaviors.Add(new WebHttpBehavior());
var client = channelFactory.CreateChannel();
var fileModel = new Services.FileModel()
{
FileName = HttpUtility.UrlEncode(listItem.File.Name),
FileContent = listItem.File.OpenBinary(),
HoursToShare = hoursToShare,
PutFileNameInUrl = putFileNameInUri
};
var blobToken = client.ShareFile(fileModel);
((IClientChannel)client).Close();
channelFactory.Close();
this.textBoxGeneratedLink.Text = String.Format("{0}/{1}",GetServiceUrl(),blobToken);
}
catch (Exception ex)
{
SPUtility.TransferToErrorPage(String.Format("Tried to upload {0} with {1} bytes, got error {2}", listItem.File.Name, listItem.File.OpenBinary().Length, ex.Message));
}
}
示例15: ClientInitialize
private void ClientInitialize()
{
try
{
if (!_initialized)
{
_serverUri = new Uri(ItemServiceUrl);
Logger.Log("Initializing Client Service connection to {0}", _serverUri.AbsoluteUri);
WebHttpBinding webHttpBinding = new WebHttpBinding
{
OpenTimeout = TimeSpan.FromMilliseconds(5000),
SendTimeout = TimeSpan.FromMilliseconds(5000),
CloseTimeout = TimeSpan.FromMilliseconds(5000),
};
_httpFactory = new WebChannelFactory<IItemService>(webHttpBinding, _serverUri);
_httpProxy = _httpFactory.CreateChannel();
_initialized = true;
}
}
catch (Exception ex)
{
Logger.Log("Exception in ClientInitialize() {0}", ex);
}
}