2011-04-08 9 views
5

Sé que parece que esta pregunta se ha publicado muchas veces, pero he leído casi todas (la mayoría de los tutoriales en Internet), y Todavía no puedo entender lo que estoy haciendo mal.Llamar a un servicio ASP.NET 4.0 WCF de jQuery produce 400 Bad Request

Intenté implementar en un sitio web que estamos desarrollando un servicio web WCF para ser consumido por un script jQuery, pero sigo obteniendo 400 Bad Request al hacer la solicitud AJAX, y estoy empezando a perder la esperanza.

Tenga en cuenta que soy nuevo en WCF, y me formé solo a través de tutoriales en línea, por lo que es completamente posible pasar por alto o principalmente arruinar algo.

Preguntas que intentaron, pero no ayudan:

r externa esources he leído en vano:

También probé la creación de una nueva solución, con solo una página y el servicio, para gobernar interferencias, pero todavía tengo el mismo problema. Aquí puede encontrar el código:

IService.cs

namespace WebService 
{ 
    using System; 
    using System.ServiceModel; 
    using System.ServiceModel.Web; 

    [ServiceContract(Name = "Service", Namespace = "WebService")] 
    public interface IService 
    { 
     [OperationContract] 
     [WebInvoke(BodyStyle = WebMessageBodyStyle.Wrapped, Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] 
     String Test(); 
    } 
} 

Service.svc.cs

namespace WebService 
{ 
    using System; 

    public class Service : IService 
    { 
     public String Test() 
     { 
      return "Hello, world."; 
     } 
    } 
} 

Default.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebService.Default" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head runat="server"> 
     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript"></script> 
     <script type="text/javascript"> 
      $(document).ready(function() { 
       $("#doAjax").click(function (event) { 
        event.preventDefault(); 
        jQuery.ajax({ 
         contentType: "application/json" 
         , dataType: "text" 
         , error: function (jqXHR, textStatus, errorThrown) { 
          console.group("AJAX error:"); 
          console.debug(jqXHR); 
          console.debug(textStatus); 
          console.groupEnd(); 
         } 
         , processData: false 
         , success: function (data, textStatus, jqXHR) { 
          console.group("AJAX success:"); 
          console.debug(data); 
          console.debug(textStatus); 
          console.debug(jqXHR); 
          console.groupEnd(); 
         } 
         , type: "post" 
         , url: "/Service.svc/Test" 
        }); 
       }); 
      }); 
     </script> 
     <title>WebService</title> 
    </head> 
    <body> 
     <form runat="server"> 
      <h1><%= this.Page.Title %></h1> 
      <p><input id="doAjax" type="button" value="Run" /></p> 
     </form> 
    </body> 
</html> 

Web.config

<?xml version="1.0" encoding="utf-8"?> 
<configuration> 
    <system.web> 
     <compilation debug="true" targetFramework="4.0" /> 
    </system.web> 
    <system.serviceModel> 
     <bindings /> 
     <client /> 
     <behaviors> 
      <endpointBehaviors> 
       <behavior name="Behavior"> 
        <webHttp /> 
       </behavior> 
      </endpointBehaviors> 
      <serviceBehaviors> 
       <behavior name=""> 
        <serviceMetadata httpGetEnabled="true" /> 
        <serviceDebug includeExceptionDetailInFaults="false" /> 
       </behavior> 
      </serviceBehaviors> 
     </behaviors> 
     <serviceHostingEnvironment multipleSiteBindingsEnabled="true" /> 
     <services> 
      <service name="Service"> 
       <endpoint behaviorConfiguration="Behavior" binding="webHttpBinding" contract="WebService.IService" /> 
      </service> 
     </services> 
    </system.serviceModel> 
</configuration> 
+0

¿Encontró una respuesta a esta pregunta? Estoy teniendo el mismo problema y no pude encontrar la solución ... :( –

+0

@NaveedButt no, y desde entonces me he mudado a otros proyectos. Pruebe las respuestas a continuación, y si puede hacerlo, publique una respuesta/comentario para que otros puedan saber qué hacer. – Albireo

+0

Puedo ver más detalles sobre el error colocando un div en la página y estableciendo su html en jqXHR en caso de error. De esta manera, se me presenta un mejor resultado. se publicará una solución aquí, cuando encuentro un IA. –

Respuesta

1

Hey! Estaba teniendo el mismo problema (... otra vez) pero finalmente lo descubrí y lo puse en funcionamiento correctamente.

Ahora bien, esta es mi propio ejemplo, pero debido a que trabajó para mí, es de esperar que va a trabajar para usted también ... La línea clave que me estaba olvidando estaba en mi comando $ ajax:

contentType: "application/json; charset=utf-8" 

Buena suerte :) Pasé medio día en este tema.

interfaz:

[OperationContract] 
[WebInvoke(ResponseFormat = WebMessageFormat.Json)] 
int CreateMilestone(Milestone Input); 

Clase:

[DataContract] 
public class Milestone 
{ 
    [DataMember] 
    public string Name { get; set; } 
    [DataMember] 
    public string Date { get; set; } 
    [DataMember] 
    public int Risk { get; set; } 
    [DataMember] 
    public int Complexity { get; set; } 
} 

el método:

public int CreateMilestone(Milestone Input) 
    { 
     return 0; 
    } 

la jquery:

$("#btnSubmit").click(function() { 

    if ($.trim($("#txtName").val()) == "") { 
     $("#dName").effect("highlight", 500); 
    } 
    else { 

     var date = $("#txtDate").datepicker("getDate"); 
     var data = { 
      Name: $("#txtName").val(), 
      Date: (date.getMonth() + 1) + "-" + date.getDate() + "-" + date.getFullYear(), 
      Risk: parseInt($("#sRisk").text()), 
       Complexity: parseInt($("#sComplexity").text()) 
      }; 
      var jsondata = JSON.stringify(data); 
      $.ajax({ 
       type: "POST", 
       async: false, 
       url: 'Services/ProjectService.svc/CreateMilestone', 
       contentType: "application/json; charset=utf-8", 
       data: jsondata, 
       dataType: "json", 
       success: function (msg) { 
       }, 
       error: function (XMLHttpRequest, textStatus, errorThrown) { 
        //      alert(XMLHttpRequest.status); 
        //      alert(XMLHttpRequest.responseText); 
       } 
      }); 
     } 
    }); 
2

El nombre del servicio debe estar totalmente calificado. Intente: <service name="WebService.Service">

Cuestiones relacionadas