2011-12-08 23 views
8

Al intentar crear un servicio simple para devolver una cadena JSON simple siguiendo varios tutoriales. Me quedo atrapado en dos máquinas diferentes con una solicitud incorrecta HTTP Statuscode 400. Ejemplo tutoriales REST servicio WCF con JSON pt.1 & pt.2 - http://www.youtube.com/watch?v=5BbDxB_5CZ8C# 4.0 WCF REST JSON - HTTP OBTENGA EL CÓDIGO 400 Solicitud incorrecta

que tienen también Google y buscaron aquí (StackOverflow) para un problema similar sin éxito.

El problema es que recibo la solicitud 400 incorrecta al intentar hacer una comprobación de cordura para navegar al servicio WCF y ejecutar el método. Al compilar el servicio y buscar esta dirección: http://localhost:49510/Service1.svc/GetPerson Al igual que en el tutorial. Intenté encontrar una solución por 3 días. Cualquier ayuda es apreciada.

Esto es lo que hago.

Primero creo un proyecto nuevo una aplicación de servicio WCF simple. Elimino el valor por defecto Service1.svc y añadir un nuevo servicio WCF, que generan un nuevo Service1.svc y una IService1.cs

Este es el código para la interfaz (IService1.cs)

namespace WcfService1 
{ 
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together. 
    [ServiceContract] 
    public interface IService1 
    { 
     [OperationContract] 
     [WebInvoke(Method="GET", BodyStyle=WebMessageBodyStyle.Bare, ResponseFormat=WebMessageFormat.Json, RequestFormat=WebMessageFormat.Json, UriTemplate="GetPerson")] 
     Person GetPerson(); 
    } 

    [DataContract(Name="Person")] 
    public class Person 
    { 
     [DataMember(Name="name")] 
     public string Name { get; set; } 
    } 
} 

Aquí está el código para el Service1.svc

namespace WcfService1 
{ 
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together. 
    public class Service1 : IService1 
    { 
     public Person GetPerson() 
     { 
      return new Person() { Name = "Tobbe" }; 
     } 
    } 
} 

y el Web.config es virgen y le gusta mirar este web.config

<?xml version="1.0"?> 
<configuration> 

    <system.web> 
    <compilation debug="true" targetFramework="4.0" /> 
    </system.web> 
    <system.serviceModel> 
    <behaviors> 
     <serviceBehaviors> 
     <behavior> 
      <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --> 
      <serviceMetadata httpGetEnabled="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="false"/> 
     </behavior> 
     </serviceBehaviors> 
    </behaviors> 
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> 
    </system.serviceModel> 
<system.webServer> 
    <modules runAllManagedModulesForAllRequests="true"/> 
    </system.webServer> 

</configuration> 

Respuesta

11

para el descanso WCF tienes que hacer ajuste de la unión y el punto final en el web.config

Reemplaza toda la web.config siguiendo y funcionará

<?xml version="1.0"?> 
<configuration> 

    <system.web> 
    <compilation debug="true" targetFramework="4.0" /> 
    </system.web> 
    <system.serviceModel> 
    <protocolMapping> 
     <add scheme="http" binding="webHttpBinding"/> 
    </protocolMapping> 
    <behaviors> 
     <serviceBehaviors> 
     <behavior> 
      <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --> 
      <serviceMetadata httpGetEnabled="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="false"/> 

     </behavior> 
     </serviceBehaviors> 
     <endpointBehaviors> 
     <behavior> 
      <webHttp/> 
     </behavior> 
     </endpointBehaviors> 
    </behaviors> 
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> 
    </system.serviceModel> 
<system.webServer> 
    <modules runAllManagedModulesForAllRequests="true"/> 
    </system.webServer> 
</configuration> 

Usted fue restantes con las siguientes 2 cosas

Uso webHttpBinding (asignación de puertos HTTP predeterminado cambio en webHttpBinding)

<system.serviceModel> 
    <protocolMapping> 
     <add scheme="http" binding="webHttpBinding"/> 
    </protocolMapping> 
    <behaviors> 

<system.serviceModel> 

Especificar webHttp Punto Final Comportamientos

<system.serviceModel> 
    ----- 
    </protocolMapping> 
    <behaviors> 
     <endpointBehaviors> 
      <behavior> 
       <webHttp /> 
      </behavior > 
     </endpointBehaviors> 
    <behaviors> 
    ------ 
<system.serviceModel> 
+0

¡Acabo de copiar y pegar el archivo como dijiste! ¡Salvaste mi día! ¡Excelente! ¡Muchas gracias! – user1087261

4

no se ha especificado ningún punto final ... Por defecto, en WCF 4, se utilizará un punto final utilizando basicHttpBinding. No funcionará aquí porque es un enlace basado en SOAP. Lo que se quiere utilizar es webHttpBinding que está basada en REST ...

Aquí es cómo reemplazar la unión con WCF 4 por defecto:

<system.serviceModel> 
    <protocolMapping> 
    <add scheme="http" binding="webHttpBinding"/> 
    </protocolMapping> 
</system.serviceModel> 

También tiene que habilitar webHttp mediante la adición de este comportamiento en su punto final config:

<behaviors> 
    <endpointBehaviors> 
     <behavior> 
      <webHttp /> 
     </behavior > 
    </endpointBehaviors> 
<behaviors> 

http://msdn.microsoft.com/en-us/library/bb924425.aspx

0

No estoy del todo seguro por qué, pero cuando agregué el atributo 'Factory' a mi archivo .SVC (debe arrastrarlo explícitamente a Visual Studio), todo simplemente funciona - sin ningún cambio en el valor predeterminado configuración en Web.config!

que añade fábrica = "System.ServiceModel.Activation.WebServiceHostFactory" por lo que mi archivo .SVC pasó de esto:

<%@ ServiceHost Language="C#" Debug="true" Service="ServiceNameSpace.ServiceName" CodeBehind="ServiceName.svc.cs" %>

a esto:

<%@ ServiceHost Language="C#" Debug="true" Service="ServiceNameSpace.ServiceName" CodeBehind="ServiceName.svc.cs" Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>

El El único efecto secundario parece ser que cuando haces clic en el archivo .SVC en el navegador, obtienes un error de "Punto final no encontrado", pero el servicio funciona bien cuando estás en voke correctamente de todos modos. Como mencioné anteriormente, estoy usando un Web.config predeterminado con .NET 4.6 (Simplified WCF configuration), por lo que es posible que aún tenga que agregar detalles del punto final para que funcione nuevamente.

Nota para el moderador: mis excusas para publicar esta respuesta en un par de preguntas. No lo hare de nuevo Sin embargo, no creo que eliminarlo de AMBAS preguntas sea muy equilibrado. Es por eso que he vuelto a publicar esta respuesta solo aquí.

Cuestiones relacionadas