2014-02-21 2 views
0

У меня есть 2 проекта (проект WCF и проект Asp.Net). Я выполнил этот урок here.Веб-сервис WCF и Javascript

В этом уроке мы реализуем все в одном проекте (см. Источники here).

У меня есть ссылка на мой проект WCF в веб-проекте.

Я пытаюсь отобразить значение в своем оповещении, но ничего нет.

Вот мой Service1.svc:

namespace WSSage100{ 
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] 
public class Service1 : IService1 
{ 
    public string GetData(int value) 
    { 
     return string.Format("You entered: {0}", value); 
    } 

    public string GetData2(int value) 
    { 
     return string.Format("You entered: {0}", value); 
    } 


    public string[] GetUser(string Id) 
    { 
     return new User().GetUser(Convert.ToInt32(Id)); 
    } 

    public string GetTEST() 
    { 
     return "OKKKKKKKK"; 
    } 
} 

Вот IService1.cs:

namespace WSSage100 
{ 

[XmlSerializerFormat] 
[ServiceContract(Namespace ="WSSage100")] 
public interface IService1 
{ 

    [OperationContract] 
    [WebInvoke(Method = "GET",ResponseFormat = WebMessageFormat.Json)] 
    string GetData(int value); 


    [OperationContract] 
    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json)] 
    string GetData2(int value); 

    [OperationContract] 
    [WebInvoke(Method = "POST",BodyStyle = WebMessageBodyStyle.Wrapped,ResponseFormat = WebMessageFormat.Json)] 
    string[] GetUser(string Id); 

    [OperationContract] 
    [WebInvoke(Method = "GET",ResponseFormat = WebMessageFormat.Json)] 
    string GetTEST(); 

Вот мой веб-страницы (ASPX) с кодом JavaScript:

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head id="Head1" runat="server"> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<script language="javascript" type="text/javascript" src="JavaScript/jquery-1.10.2.min.js"></script> 

<script type="text/javascript"> 

    var Type; 
    var Url; 
    var Data; 
    var ContentType; 
    var DataType; 
    var ProcessData; 

    function WCFJSON() { 
     var userid = "1"; 
     Type = "POST"; 
     Url = "Service1.svc/GetUser"; 
     Data = '{"Id": "' + userid + '"}'; 
     ContentType = "application/json; charset=utf-8"; 
     DataType = "json"; varProcessData = true; 
     CallService(); 
    } 

    function CallService() { 
     $.ajax({ 
      type: Type, //GET or POST or PUT or DELETE verb 
      url: Url, // Location of the service 
      data: Data, //Data sent to server 
      contentType: ContentType, // content type sent to server 
      dataType: DataType, //Expected data format from server 
      processdata: ProcessData, //True or False 
      success: function (msg) {//On Successfull service call 
       ServiceSucceeded(msg); 
      }, 
      error: ServiceFailed// When Service call fails 
     }); 
    } 

    function ServiceFailed(result) { 
     alert('Service call failed: ' + result.status + '' + result.statusText); 
     Type = null; 
     varUrl = null; 
     Data = null; 
     ContentType = null; 
     DataType = null; 
     ProcessData = null; 
    } 

    function ServiceSucceeded(result) { 
     if (DataType == "json") { 
      resultObject = result.GetUserResult; 

      for (i = 0; i < resultObject.length; i++) { 
       alert(resultObject[i]); 
      } 

     } 

    } 

    function ServiceFailed(xhr) { 
     alert(xhr.responseText); 

     if (xhr.responseText) { 
      var err = xhr.responseText; 
      if (err) 
       error(err); 
      else 
       error({ Message: "Unknown server error." }) 
     } 

     return; 
    } 

    $(document).ready(
     function() { 
      WCFJSON(); 
     } 
    ); 
</script> 
<style type="text/css"> 
    #form1 { 
     height: 255px; 
    } 
</style> 

</head> 
<body> 
    <form id="form1" runat="server"> 

    <div></div> 
    </form> 
</body> 
</html> 

Вот Сервис1.svc в моем веб-проекте:

<%@ ServiceHost Language="C#" Debug="true" Service="WSSage100.Service1"%> 

Вот мой web.config в моем веб-проекта:

<configuration> 
<system.web> 
    <compilation debug="true" targetFramework="4.5" /> 
    <httpRuntime targetFramework="4.5" /> 

</system.web> 

<system.serviceModel> 
    <client> 
     <endpoint address="http://localhost:52768/Service1.svc" binding="basicHttpBinding" 
      bindingConfiguration="BasicHttpBinding_IService1" contract="WebServiceSage100.IService1" 
      name="BasicHttpBinding_IService1" /> 
    </client> 
    <behaviors> 
     <serviceBehaviors> 
      <behavior name=""> 
       <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" /> 
       <serviceDebug includeExceptionDetailInFaults="false" /> 
      </behavior> 
     </serviceBehaviors> 
     <endpointBehaviors> 
     <behavior name="EndpBehavior"> 
      <webHttp/> 
     </behavior> 
     </endpointBehaviors> 
    </behaviors> 
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" 
     multipleSiteBindingsEnabled="true" /> 
    <bindings> 
     <basicHttpBinding> 
      <binding name="BasicHttpBinding_IService1" /> 
     </basicHttpBinding> 
    </bindings> 

    <services> 
    <service name="WSSage100.Service1"> 
     <endpoint address="" binding="webHttpBinding" contract="WSSage100.IService1"> 
     </endpoint> 
    </service> 
    </services> 

    </system.serviceModel> 
</configuration> 

Брайаном, локальный: 52768/Service1.svc дисплей

enter image description here

У меня есть эта ошибка при использовании кода элемента enter image description here

Я новичок в этом домене и извиняюсь за мой плохой английский.

+0

любая ошибка в консоли? – iJade

+0

У меня есть ошибка. – Jayce

+0

Если вы наберете http: //localhost:52768/Service1.svc в адресной строке браузера, что вы получите в ответ? – Brian

ответ

0

У меня было 2 проекта в моем решении, WCF и консоль приложений (GettingStartedHost), которые будут делать, чтобы вернуть веб-службу.

Я также добавил соединительные строки в app.config проекта GettingStartedHost, и теперь он работает хорошо.

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