この投稿を通過した後でも wcf REST Services and JQuery Ajax Post: Method not allowed (3)
I cannot get past 405: Method not allowed というメッセージが表示され、次の AJAX 呼び出しを介して WCF REST サービスでメソッドを呼び出そうとしました。
$.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 ファイルを webservice プロジェクトに追加し、次のメソッド メソッドも追加しました。
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);
}
Chrome または IE で「 http://mydomain.com/service1/service.svc/json/getsupportedagencies 」という URL を投稿すると、正しいサーバー応答が JSON 形式で返されます。
はい、これをすべて実行しても、まだ 405: method not allowed が表示されます。
ティア。