Нет ajax-вызова службы WCF с помощью метода

Я отправляю простой вызов ajax с помощью метода WCF, когда он возвращает bad-request, но без метода он показывает статус успеха

Вызов Ajax

$(document).ready(function(){
            $.get("http://localhost:1347/Service1.svc/DoWork", //this shows bad-request
          //$.get("http://localhost:1347/Service1.svc", //this shows success
function(data, status){

                alert("Data: " + data + "\nStatus: " + status);
        });

Операционный контракт

namespace WcfService1
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        string DoWork();
    }
}

Реализация

public class Service1 : IService1
    {

        public string DoWork()
        {
            return string.Format("This is DoWork()");
        }
    }

Global.asax

protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }

Web.Config (изменить)

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

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true"/>
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5.2"/>
    <httpRuntime targetFramework="4.5.2"/>
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"/>
    </httpModules>
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
        <add binding="basicHttpsBinding" scheme="https"/>
    </protocolMapping>    
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
  </system.serviceModel>
  <system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
      <remove name="ApplicationInsightsWebTracking"/>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"
        preCondition="managedHandler"/>
    </modules>


    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->
    <directoryBrowse enabled="true"/>
    <validation validateIntegratedModeConfiguration="false"/>




  </system.webServer>

</configuration>

person Mangrio    schedule 18.08.2016    source источник
comment
Выполнение запроса к Service1.svc сильно отличается от Service1.svc/DoWork, так как первый вернет информационную страницу о сервисе, а второй выполнит метод.   -  person smoksnes    schedule 18.08.2016
comment
как выполнить второй?   -  person Mangrio    schedule 18.08.2016
comment
Можете ли вы перейти на localhost:1347/Service1.svc/DoWork с помощью браузера, например. Хром?   -  person smoksnes    schedule 18.08.2016
comment
прикрепите конфиг сюда я думаю проблема в конфиге   -  person Amarnath R Shenoy    schedule 18.08.2016
comment
показывает пустой экран в хроме с этой ошибкой в ​​​​консоли Failed to load resource: the server responded with a status of 400 (Bad Request)   -  person Mangrio    schedule 18.08.2016
comment
Вы создали элемент webHttpBinding в своем файле web.config?   -  person João Lourenço    schedule 18.08.2016
comment
BasicHttpBinding для этого будет достаточно, создание привязки — самая важная часть в настройке WCF-сервиса. прикрепите файл конфигурации сюда.   -  person Amarnath R Shenoy    schedule 18.08.2016
comment
добавлен конфиг @AmarnathRShenoy и JoãoLourenço   -  person Mangrio    schedule 18.08.2016
comment
@QadeerMangrio, обращая внимание на это, может помочь вам stackoverflow.com/questions/21970848/   -  person Shakir Ahamed    schedule 18.08.2016


Ответы (1)


Во-первых, убедитесь, что вы включили GET в своем контракте.

namespace WcfService1
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebGet(UriTemplate = "DoWork", ResponseFormat = WebMessageFormat.Json)]
        string DoWork();
    }
}

И затем обязательно добавьте webHttp в свой конфиг.

  <endpointBehaviors>
    <behavior>
      <webHttp />
    </behavior>
  </endpointBehaviors>

Вам также может потребоваться установить привязку к webHttpBindig.

Обычно я определяю свои конечные точки, но думаю, что вы можете обойтись и без них. Это должен быть полный пример.

  <system.serviceModel>
    <services>
      <service name="WcfService1.IService1" behaviorConfiguration="myServiceBehavior">
        <endpoint address="" binding="webHttpBinding" behaviorConfiguration="myWebBehavior" contract="WcfService1.IService1" />
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="myWebBehavior">
          <webHttp />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="myServiceBehavior">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <protocolMapping>
      <add binding="basicHttpsBinding" scheme="https"/>
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"/>
  </system.serviceModel>

Полный пример можно найти здесь.

http://www.codeproject.com/Articles/105273/Create-RESTful-WCF-Service-API-Step-By-Step-Guide

person smoksnes    schedule 18.08.2016
comment
Да, это было неправильно. webHttp это endpointbehavior. Я обновил полный пример. - person smoksnes; 18.08.2016
comment
следуя примеру в ссылке, которую вы предоставили. Я сделал то же самое с этой ссылкой в ​​браузере localhost:3700/TestService.svc/json/123 перенастроил это Failed to load resource: the server responded with a status of 405 (Method Not Allowed) - person Mangrio; 18.08.2016
comment
С предоставленным решением вы сможете вызывать localhost:1347/Service1.svc/DoWork. Но не передавать параметры с косой чертой в конце. - person smoksnes; 18.08.2016
comment
однако это мне очень помогло, почти я могу сказать, что принято. - person Mangrio; 18.08.2016