Служба WCF REST возвращает 405: метод, недопустимый для jQuery AJAX GET

Даже после прочтения этого сообщения wcf REST Services и JQuery Ajax Сообщение: Метод запрещен (3)

Я не могу пройти 405: метод не разрешен при попытке вызвать метод в моей службе WCF REST с помощью следующего вызова AJAX:

$.ajax({
    type: "GET",
    url: 'http://mydomain.com/service1/service.svc/json/getsupportedagencies',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    failure: function (msg) {
        alert(msg);
    },
    success: function (agencies) {
        alert("success via REST");
        $.each(agencies, function (i, a) {
            viewModel.agencies.push(new agency(a.Name, a.FullName));
        });
    }
});

Сервисный интерфейс определяется следующим образом:

 [ServiceContract]
public interface IService1
{
    [OperationContract]
    [WebInvoke(Method = "GET",
        RequestFormat = WebMessageFormat.Json,
       ResponseFormat = WebMessageFormat.Json, UriTemplate = "getsupportedagencies")]
    AgencyDTO[] GetSupportedAgencies();

  // other methods
}

После того, как я столкнулся с потоками по междоменным проблемам, я вручную добавил файл Global.asax в проект веб-службы, а также добавил следующий метод метода:

 protected void Application_BeginRequest(object sender, EventArgs e)
    {
        HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin",
                         "http://localhost:80");

        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 выглядит так:

<system.serviceModel>       
        <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />     
        <services>
            <service behaviorConfiguration="ServiceBehavior" name="Services.Service1">
                <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
                <endpoint address="basic" binding="basicHttpBinding" contract="Services.Contracts.IService1" />
                <endpoint address="json" 
                    behaviorConfiguration="JsonBehavior"
                    binding="webHttpBinding" 
                    contract="Services.Contracts.IService1" />
            </service>   
        </services>
        <behaviors>
        <endpointBehaviors>
            <behavior name="JsonBehavior">
                <webHttp />
            </behavior>
        </endpointBehaviors>
    <serviceBehaviors>
    <behavior name="ServiceBehavior">
     <serviceMetadata httpGetEnabled="true" />
     <serviceDebug includeExceptionDetailInFaults="true" />
    </behavior>
   </serviceBehaviors>
  </behaviors>      
    </system.serviceModel>

Мой модульный тест для службы с использованием следующего кода проходит:

[Test]
 public void TestGetAgencyForLocation()
       {
           var client = new WebClient();

           var response = client.DownloadString(
                  "http://mydomain.com/service1/service.svc/json/getsupportedagencies");
           Assert.IsTrue(!string.IsNullOrEmpty(response));

           var agencies= JsonConvert.DeserializeObject(response);
           Assert.IsNotNull(agencies);
       }

Если я отправлю URL "http://mydomain.com/service1/service.svc/json/getsupportedagencies "в Chrome или IE, я получаю правильный ответ сервера в формате JSON.

Да, со всем этим я все еще получаю 405: метод не разрешен.

TIA.


person Klaus Nji    schedule 09.04.2012    source источник
comment
Спасибо, что решили мою проблему с этой строкой HttpContext.Current.Response.AddHeader (Access-Control-Allow-Methods, GET, POST);   -  person MR.ABC    schedule 01.04.2013


Ответы (1)


Я решил эту проблему, добавив приведенный ниже код в файл Global.asax проекта WCF.

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", "POST, PUT, DELETE");

                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }
person Anjan Kant    schedule 29.05.2017