我有一个WCF服务,其中所有内容都是以编程方式启动的(并且需要继续这样做),我希望此服务能够响应[WebGet]
属性。
但是,当我调用其中一个WCF方法时,该服务返回400 Bad Request。
这最初似乎是WCF Service Returns 400 error when using WebGet或Bad Request 400 while accessing WCF Rest service (WebGet)的副本,但这两个解决方案都添加到web.config
,这是我没有的文件,因为我需要以编程方式执行所有操作。
我试图将WebHttpBinding添加到看似端点的东西,但它无法正常工作(我可能没有以正确的方式进行)。
下面的代码启动没有错误,但当我尝试转到http://localhost:8765/MyService/MyTest
时,我得到上述400 Bad Request
我错过了什么?
WCF启动器
MyService myService = new MyService();
ServiceHost host = new ServiceHost(myService, new Uri("http://localhost:8765/MyService"));
ServiceBehaviorAttribute behavior = host.Description.Behaviors.Find<ServiceBehaviorAttribute>();
behavior.InstanceContextMode = InstanceContextMode.Single;
foreach(ServiceEndpoint endpoint in host.Description.Endpoints) {
endpoint.Binding = new WebHttpBinding();
}
host.Open();
服务界面
[ServiceContract]
public interface IMyService {
[OperationContract]
[WebGet]
string MyTest();
}
服务实施
public class MyService : IMyService {
public string MyTest() {
return "Response from WCF service";
}
}
答案 0 :(得分:1)
我使用我编写的代码来初始化并从代码中完全启动我的WCF restful服务:
public static WebServiceHost InitializeAndStartWebServiceHost(int port, string endPointName, object serviceModel, Type implementedContractType) {
var baseAddress = new Uri($"http://0.0.0.0:{port}/{endPointName}");
WebServiceHost host;
try {
host = new WebServiceHost(serviceModel, baseAddress);
} catch (Exception exception) {
Debug.Print("Error when creating WebServiceHost, message: " + exception.Message);
return null;
}
// ReSharper disable once UseObjectOrCollectionInitializer
var binding = new WebHttpBinding();
binding.UseDefaultWebProxy = false;
binding.BypassProxyOnLocal = true;
//By default, TransferMode is Buffered which causes C# wcf client to be slow as hell (>500ms for requests which give >2kB responses).
//I am not exactly sure why this helps, but it helps!
binding.TransferMode = TransferMode.Streamed;
host.AddServiceEndpoint(implementedContractType, binding, "");
var behavior = new WebHttpBehavior();
behavior.HelpEnabled = false;
behavior.DefaultBodyStyle = WebMessageBodyStyle.Bare;
// We will use json format for all our messages.
behavior.DefaultOutgoingRequestFormat = WebMessageFormat.Json;
behavior.DefaultOutgoingResponseFormat = WebMessageFormat.Json;
behavior.AutomaticFormatSelectionEnabled = false;
behavior.FaultExceptionEnabled = true;
host.Description.Endpoints[0].Behaviors.Add(behavior);
try {
host.Open();
} catch (AddressAccessDeniedException) {
Console.WriteLine(@"Application must run with administrator rights.");
Console.ReadKey();
Environment.Exit(0);
}
return host;
}