[英]WCF service with WebGet doesn't work
我有一個WCF服務,其中所有內容[WebGet]
編程方式啟動(並且需要繼續這樣做),並且我希望該服務響應[WebGet]
屬性。
但是,當我調用WCF方法之一時,該服務將返回400 Bad Request。 最初看起來像WCF服務的復制品, 當使用WebGet或訪問WCF Rest服務(WebGet) 時出現 Bad Request 400時 返回400錯誤,但是這兩個解決方案都添加到了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";
}
}
我使用編寫的以下代碼完全從代碼初始化和啟動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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.