2011-04-08 25 views
5

So che sembra che questa domanda sia stata postata molte volte, ma ho letto quasi tutte (una gran parte delle esercitazioni su Internet), e Non riesco ancora a capire cosa sto sbagliando.Chiamare un servizio WCF di ASP.NET 4.0 da jQuery produce 400 Richiesta errata

Ho provato a implementare in un sito Web che stiamo sviluppando un servizio Web WCF per essere utilizzato da uno script jQuery, ma continuo a ricevere 400 Bad Request quando faccio la richiesta AJAX e sto iniziando a perdere le speranze.

Si noti che sono nuovo a WCF e mi sono formato solo attraverso esercitazioni online, quindi è del tutto possibile trascurare o rovinare qualcosa.

Domande Ho provato, ma non ha aiutato:

r esterno isorse ho letto senza alcun risultato:

Ho provato anche la creazione di una nuova soluzione, con solo una pagina e il servizio, da governare fuori interferenze, ma ho ancora lo stesso problema. Qui è possibile trovare il codice:

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

Ti è venuta una risposta a questa domanda? Sto avendo lo stesso problema e non ho potuto trovare la soluzione ... :( –

+0

@NaveedButt no, e da allora mi sono trasferito in altri progetti. Prova le risposte qui sotto, e se sei in grado di farlo, pubblica una risposta/commento così altri possono sapere cosa fare – Albireo

+0

Sono in grado di vedere alcuni dettagli sull'errore inserendo un div nella pagina e impostando il suo html su jqXHR in caso di errore generato, in questo modo mi viene presentato un output migliore. pubblicherò una soluzione qui, quando trovo un IA. –

risposta

1

Hey! Stavo avendo lo stesso problema (ancora una volta) ma alla fine l'ho capito e ho funzionato correttamente.

ora questo è il mio esempio, ma perché ha funzionato per me, spero che funzionerà anche per te ... La linea di chiave che stavo dimenticando era in mio comando $ AJAX:

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

Buono fortuna :) Ho passato mezza giornata a questo problema.

interfaccia:

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

Classe:

[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; } 
} 

il metodo:

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

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

Il nome del servizio deve essere completo. Prova: <service name="WebService.Service">

Problemi correlati