簡體   English   中英

使用WCF調用的Ajax返回404錯誤

[英]Ajax with WCF call returns 404 Error

我想使用Ajax調用來調用WCF服務,但它會返回404錯誤未找到錯誤

可通過瀏覽器訪問該URL,並且打開端口1506

這是我的Ajax電話:我想使用POST類型

$.ajax(
    {
       contentType: "application/json; charset=utf-8",
       dataType: "json",
       url: "http://192.168.80.18:1506/Service1.svc/GetData",
       type: 'POST',
       success: function (data, status, xhr)
       {
           alert('Success: '+data);
       },                        
       error: function(x, e)
       {
           if (x.status == 0) {
                    alert('You are offline!!\n Please Check Your Network.');
                } else if (x.status == 404) {
                    // Here is the problem
                    alert('Requested URL not found.');
                } else if (x.status == 500) {
                    alert('Internal Server Error.');
                } else if (e == 'parsererror') {
                    alert('Error.\nParsing JSON Request failed.');
                } else if (e == 'timeout') {
                    alert('Request Time out.');
                } else {
                    alert('Unknow Error.\n' + x.responseText);
                }
       }
    });

WCF端

IService1.cs在這里,我添加了POST方法[ServiceContract]公共接口IService1 {

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

    [OperationContract]
    CompositeType GetDataUsingDataContract(CompositeType composite);

    // TODO: ajoutez vos opérations de service ici
}

服務1.svc

public class Service1 : IService1
{
    public string GetData()
    {
        return "Hello world!";
    }
}

Web.config

    <?xml version="1.0" encoding="utf-8"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5"/>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- Pour éviter la divulgation d'informations de métadonnées, définissez les valeurs ci-dessous sur false avant le déploiement -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- Pour recevoir les détails de l'exception dans les erreurs à des fins de débogage, définissez la valeur ci-dessous sur true. Pour éviter la divulgation d'informations d'exception, définissez-la sur false avant le déploiement -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service name="WcfService1.Service1">
        <endpoint address="Service1.svc"
                  binding="basicHttpBinding"
                  contract="WcfService1.IService1" />
      </service>
    </services>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        Pour parcourir le répertoire racine de l'application Web lors du débogage, définissez la valeur ci-dessous sur true.
        Définissez-la sur false avant le déploiement pour ne pas divulguer d'informations du dossier de l'application Web.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>
</configuration>

使用工具進行一些測試以驗證您的問題。 我通常使用Postman 它允許您構造POST消息並針對端點測試它,這是確定問題實際原因的最佳方法。

我找到了解決方案,現在可以使用了。在這種情況下,請不要忘記將3070端口設置為防火牆設置

如果要從另一台計算機訪問服務,則可以更改applicationhost.xml文件

IService1.cs在這里,我添加了ResponseFormat(JSON),RequestFormat(JSON)和UriTemplate來通過url訪問我的函數: http : //192.168.80.18 :3070/Service1.svc/ GetData

public interface IService1
{

    [OperationContract]
    [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, RequestFormat=WebMessageFormat.Json,UriTemplate="/getdata")]
    string GetData();

    [OperationContract]
    CompositeType GetDataUsingDataContract(CompositeType composite);
}

Service1.svc.cs此處無更改

public class Service1 : IService1
{
    public string GetData()
    {
        return "It works";
    }

    public CompositeType GetDataUsingDataContract(CompositeType composite)
    {
        if (composite == null)
        {
            throw new ArgumentNullException("composite");
        }
        if (composite.BoolValue)
        {
            composite.StringValue += "Suffix";
        }
        return composite;
    }
}

Web.config在這里,我添加了帶有endpointBehaviors的 服務標簽,以在其中添加webHttp標簽

    <?xml version="1.0" encoding="utf-8"?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" maxUrlLength="500"/>
  </system.web>
  <system.serviceModel>
    <services>
        <service name="WcfService2.Service1">
            <!-- Service Endpoints -->
            <endpoint address="" binding="webHttpBinding" contract="WcfService2.IService1" behaviorConfiguration="webBehavior">
            </endpoint>
        </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="webBehavior">
          <webHttp />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior>
          <!-- Pour éviter la divulgation d'informations de métadonnées, définissez les valeurs ci-dessous sur false avant le déploiement -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- Pour recevoir les détails de l'exception dans les erreurs à des fins de débogage, définissez la valeur ci-dessous sur true. Pour éviter la divulgation d'informations d'exception, définissez-la sur false avant le déploiement -->
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https" />
    </protocolMapping>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
    <!--
        Pour parcourir le répertoire racine de l'application Web lors du débogage, définissez la valeur ci-dessous sur true.
        Définissez-la sur false avant le déploiement pour ne pas divulguer d'informations du dossier de l'application Web.
      -->
    <directoryBrowse enabled="true"/>
  </system.webServer>

</configuration>

Ajax端這里沒有重大變化

$.ajax(
    {
       contentType: "application/json; charset=utf-8",
       dataType: "json",
       url: "http://192.168.80.18:3070/Service1.svc/GetData",
       type: 'GET',
       data: "{}",
       success: function (data, status, xhr)
       {
           alert('Success: '+data);
       },                        
       error: function(x, e)
       {
           if (x.status == 0) {
                    alert('You are offline!!\n Please Check Your Network.');
                } else if (x.status == 404) {
                    alert('Requested URL not found.');
                } else if (x.status == 500) {
                    alert('Internal Server Error.');
                } else if (e == 'parsererror') {
                    alert('Error.\nParsing JSON Request failed.');
                } else if (e == 'timeout') {
                    alert('Request Time out.');
                } else {
                    alert('Unknow Error.\n' + x.responseText);
                }
       }
    });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM