Не получать ответ на ajax-вызов веб-службы wcf вне этого проекта службы - PullRequest
0 голосов
/ 03 августа 2011

Я новичок в сервисе wcf и .net. Я создаю 1 тестовый сервис wcf. Я могу получить ответ ajax, если я положил файл в тот же каталог проекта. Если я вызвал его из директории проекта с помощью URL, то я не получил ответа. Это интерфейсный файл

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Data;
using System.Web.Script.Services;

namespace TestService
{
    // 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", UriTemplate = "helloworld/{name}")]
        string Helloworld(string name);

        [OperationContract]
        [WebInvoke(Method = "GET", UriTemplate = "testservice")]
        Dictionary<string,string> testService();

        [OperationContract]
        [WebInvoke(Method = "GET", UriTemplate = "getActiveComplains")]
        List<TestService.Tickets> GetActiveComplain();
    }

    [DataContract]
    public class Tickets
    {
        [DataMember]
        public string TicketNo { get; set; }

        [DataMember]
        public string TicketType { get; set; }

        [DataMember]
        public string Descriptions { get; set; }

        [DataMember]
        public string PoleNo { get; set; }

        [DataMember]
        public string Address { get; set; }


    }
}

Это файл класса

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Data.Entity;

namespace TestService
{
    // 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 string Helloworld(string name)
        {
            return "Hello World, " + name;
        }

        public Dictionary<string, string> testService()
        {
            Dictionary<string, string> test = new Dictionary<string, string>();

            test.Add("test1", "success for test1");
            test.Add("test2", "success for test2");
            test.Add("test3", "success for test3");
            test.Add("test4", "success for test4");
            test.Add("test5", "success for test5");

            return test;
        }

        public List<TestService.Tickets> GetActiveComplain()
        {
            List<TestService.Tickets> objAllTickets = new List<Tickets>();

            DataLayer.lmsTicketEntities objlmsTicketEntities = new DataLayer.lmsTicketEntities(System.Configuration.ConfigurationManager.ConnectionStrings["lmsConnectionString"].ToString().Replace("LMSModel", "TicketModel"));

            List<DataLayer.GetActiveTicket> objAllComplainTickets = objlmsTicketEntities.GetAllActiveTicket().ToList<DataLayer.GetActiveTicket>();

            foreach (var objTicket in objAllComplainTickets)
            {
                TestService.Tickets objTempTicket = new TestService.Tickets();

                objTempTicket.TicketNo = objTicket.TicketNo;
                objTempTicket.TicketType = objTicket.TicketType;
                objTempTicket.Descriptions = objTicket.TicketDescriptions;
                objTempTicket.PoleNo = objTicket.PoleNo;
                objTempTicket.Address = objTicket.Address1;

                objAllTickets.Add(objTempTicket);

            }
            return objAllTickets;
        }
    }
}

и это файл конфигурации

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

      <system.web>
        <compilation debug="true" targetFramework="4.0" />
      </system.web>

      <system.serviceModel>

    <services>
      <!-- Note: the service name must match the configuration name for the service implementation. -->
      <service name="TestService.Service1" behaviorConfiguration="MyServiceTypeBehaviors" >
        <!-- Add the following endpoint.  -->
        <!-- Note: your service must have an http base address to add this endpoint. -->
        <endpoint contract="TestService.IService1" binding="webHttpBinding"  behaviorConfiguration="webHttpBehavior" bindingConfiguration="webHttpBindingWithJsonP" />

      </service>
    </services>

    <behaviors>
      <serviceBehaviors>
        <behavior name="MyServiceTypeBehaviors" >
          <!-- Add the following element to your service behavior configuration. -->
          <serviceMetadata httpGetEnabled="true" />
        </behavior>

      </serviceBehaviors>
      <endpointBehaviors>

        <behavior name="webHttpBehavior">

          <webHttp defaultOutgoingResponseFormat="Json"/>

        </behavior>

      </endpointBehaviors>
    </behaviors>
    <bindings>
      <webHttpBinding>
        <binding name="webHttpBindingWithJsonP" crossDomainScriptAccessEnabled="true" />
      </webHttpBinding>
    </bindings>

  </system.serviceModel>
      <system.webServer>
        <modules runAllManagedModulesForAllRequests="true"/>
      </system.webServer>
    </configuration>

В этом сенарио я получаю ответ, если я добавлю этот код в сервисный проект

<!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>
    <title></title>
    <script src="jquery-1.5.1.min.js" type="text/javascript"></script>
    <script>
        $(document).ready(function () {

            $.ajax({
                type: "GET",
                url: "/Service1.svc/getActiveComplains",
                success: function (html) {
                    alert(html);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(XMLHttpRequest.message);
                    console.log(XMLHttpRequest);
                }

            });
        });
    </script>
</head>
<body>

</body>
</html>

В этом ниже senario это не работает, если я называю это стороной проекта

<!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>
    <title></title>
    <script src="jquery-1.5.1.min.js" type="text/javascript"></script>
    <script>
        $(document).ready(function () {

            $.ajax({
        type: "GET",
        url: "http://localhost:3048/Service1.svc/getActiveComplains",
        success: function (html) {


        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {

            console.log(XMLHttpRequest);
        }

    });
        });
    </script>
</head>
<body>

</body>
</html>

Пожалуйста, помогите мне.

Ответы [ 2 ]

0 голосов
/ 10 августа 2011

Могут быть проблемы междоменного доступа. Попробуйте что-то вроде this .

0 голосов
/ 03 августа 2011

Либо ваша служба не работает, либо вы обнаружили ограничение - вызовы AJAX не разрешены в междоменных сценариях Обычно это решается с помощью JSONP .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...