2016-07-25 11 views
0

Я прекрасно понимаю, что эта проблема уже обсуждалась много раз, но это конкретная конфигурация моего проекта, которую я упускаю, чтобы понять, из-за чего моя связь Service-Client идет не так. Прошу вас помочь в этом вопросе. Извините мои глупые ошибки, я очень новичок в WCF и REST-сервисах вообще.WCF - Как правильно настроить MVC-клиента, использующего службу WCF?

Итак, в основном, я хочу создать приложение MVC, которое будет использовать службу REST WCF, размещенную на сервере IIS.

Я создал приложение службы WCF с помощью следующего контракта Service:

[ServiceContract] 
public interface IUserService 
{ 
    [OperationContract] 
    [WebInvoke(Method = "GET", 
     ResponseFormat = WebMessageFormat.Json, 
     RequestFormat = WebMessageFormat.Json, 
     BodyStyle = WebMessageBodyStyle.Wrapped, 
     UriTemplate = "/ListaUtilizatori/")] 
    DataSet ListaUtilizatori(); 

    [OperationContract] 
    [WebInvoke(Method = "GET", 
     ResponseFormat = WebMessageFormat.Json, 
     RequestFormat = WebMessageFormat.Json, 
     BodyStyle = WebMessageBodyStyle.Wrapped, 
     UriTemplate = "/DetaliiUtilizator/{id}")] 
    DataSet DetaliiUtilizator(String id); 


    [OperationContract] 
    [WebInvoke(Method = "POST", 
     ResponseFormat = WebMessageFormat.Json, 
     RequestFormat = WebMessageFormat.Json, 
     BodyStyle = WebMessageBodyStyle.Wrapped, 
     UriTemplate = "/AdaugaUtilizator")] 
    String AdaugaUtilizator(Utilizator utilizator); 

    [OperationContract] 
    [WebInvoke(Method = "PUT", 
     RequestFormat = WebMessageFormat.Json, 
     ResponseFormat = WebMessageFormat.Json, 
     UriTemplate = "/ActualizeazaUtilizator")] 
    String ActualizeazaUtilizator(Utilizator utilizator); 

    [OperationContract] 
    [WebInvoke(Method = "DELETE", 
     RequestFormat = WebMessageFormat.Json, 
     ResponseFormat = WebMessageFormat.Json, 
     UriTemplate = "/StergeUtilizator/{id}")] 
    String StergeUtilizator(String id); 
} 

я правильно реализованных метод и в файле web.config я настроена служба модель как таковые:

<system.serviceModel> 
    <services> 
     <service name="RESTService.UserService" behaviorConfiguration="RESTServiceBehaviour"> 
     <endpoint address="" binding="webHttpBinding" bindingConfiguration="WebHttpBinding_IUserService" contract="RESTService.IUserService" behaviorConfiguration="RESTEndpointBehavior"></endpoint> 
     </service> 
    </services> 
    <behaviors> 
     <serviceBehaviors>   
     <behavior name="RESTServiceBehaviour"> 
      <!-- To avoid disclosing metadata information, set the values below to false before deployment --> 
      <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/> 
      <!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --> 
      <serviceDebug includeExceptionDetailInFaults="true"/> 
     </behavior> 
     </serviceBehaviors> 
     <endpointBehaviors> 
     <behavior name="RESTEndpointBehavior"> 
      <webHttp helpEnabled="True"/> 
     </behavior> 
     </endpointBehaviors> 
    </behaviors> 
    <bindings> 
     <webHttpBinding> 
     <binding name="WebHttpBinding_IUserService" /> 
     </webHttpBinding> 
    </bindings> 
    <protocolMapping> 
     <add binding="webHttpBinding" scheme="http" /> 
    </protocolMapping>  
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" /> 
    </system.serviceModel> 

Впоследствии я опубликовал приложение WCF на сервере IIS, и он просто отлично возвращал ожидаемый ответ формата JSON в браузере.

Я создал приложение MVC, которому я добавил ссылку на службу для опубликованной службы WCF и назвал ее UserServiceReference. Как ни странно, ни один system.serviceModel узла не был добавлен или сконфигурирован в MVC-х web.config, поэтому я добавил вручную следующий:

<system.serviceModel> 
    <behaviors> 
     <endpointBehaviors> 
     <behavior name="RESTEndpoint"> 
      <webHttp helpEnabled="true"/> 
     </behavior> 
     </endpointBehaviors> 
    </behaviors> 
    <bindings> 
     <webHttpBinding> 
     <binding name="WebHttpBinding_IUserService" />   
     </webHttpBinding>  
    </bindings> 
    <client> 
     <endpoint address="http://localhost/RESTUserService/UserService.svc" binding="webHttpBinding" bindingConfiguration="WebHttpBinding_IUserService" 
       behaviorConfiguration="RESTEndpoint" contract="UserServiceReference.IUserService" name="WebHttpBinding_IUserService" /> 
    </client> 
</system.serviceModel> 

Затем я попытался проверить функциональность путем создания клиента в одном из контроллеров приложения с помощью следующего кода:

UserServiceReference.UserServiceClient client = new UserServiceReference.UserServiceClient(); 
      DataSet ds = client.DetaliiUtilizator("2"); 
UserServiceReference.UserDataContractUtilizator utilizator = new UserServiceReference.UserDataContractUtilizator(); 

Когда я запускаю мое приложение, я получаю эту ошибку в браузере:

[WebException: The remote server returned an error: (404) Not Found.] System.Net.HttpWebRequest.GetResponse() +1390 System.ServiceModel.Channels.HttpChannelRequest.WaitForReply(TimeSpan timeout) +55 

[EndpointNotFoundException: There was no endpoint listening at http://localhost/RESTUserService/UserService.svc/DetaliiUtilizator that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details.] 
System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg) +153 



System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type) +336 
    MVCApp.UserServiceReference.IUserService.DetaliiUtilizator(String id) +0 
    MVCApp.UserServiceReference.UserServiceClient.DetaliiUtilizator(String id) in D:\F5IT\PROJECT\RESTService\MVCApp\Service References\UserServiceReference\Reference.cs:308 
    MVCApp.Controllers.HomeController.Index() in D:\F5IT\PROJECT\RESTService\MVCApp\Controllers\HomeController.cs:34 
    lambda_method(Closure , ControllerBase , Object[]) +61 
    System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14 
    System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +157 
    System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27 
    System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22 
    System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +29 
    System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49 
    System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32 
    System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +50 
    System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +225 
    System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +10 
    System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10 
    System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49 
    System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34 
    System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +26 
    System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100 
    System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10 
    System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49 
    System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27 
    System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13 
    System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29 
    System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49 
    System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36 
    System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12 
    System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22 
    System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49 
    System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26 
    System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10 
    System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21 
    System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29 
    System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49 
    System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28 
    System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9 
    System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9744373 
    System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155 
Source Error: 

Line 306:   
Line 307:  public System.Data.DataSet DetaliiUtilizator(string id) { 
Line 308:   return base.Channel.DetaliiUtilizator(id); 
Line 309:  } 
Line 310:  

Я добавил эти вещи, как компиляции O f все сообщения, которые я прочитал. Во всем этом коде должна быть определенная ошибка. Что бы это могло быть?

Большое вам спасибо!

+0

от ошибки: 'См. InnerException, если присутствует, для более подробной информации.' –

+0

@JamieR Я добавил все исключение. – Ionna

+0

Вы уверены, что 'http: // localhost/RESTUserService/UserService.svc/DetaliiUtilizator' является правильной конечной точкой? –

ответ

0

я в конце концов понял, когда проблема была в этой статье:

https://blogs.msdn.microsoft.com/carlosfigueira/2012/03/25/mixing-add-service-reference-and-wcf-web-http-a-k-a-rest-endpoint-does-not-work/

Похоже, что при добавлении ссылки на службу к службе WCF с конечной точкой с использованием WebHttpBinding приведет к бесполезному автоматически генерируемой код клиента ,

 Смежные вопросы

  • Нет связанных вопросов^_^