まず、Microsoft Ajax ScriptManager に依存したくないため、endpointBehaviors/behavior で <enableWebScript /> を使用しないでください。これは Microsoft 固有の JSON です。
ただし、幸いなことに、WCF を使用すると、クライアントは XML と汎用 JSON のどちらが必要かを非常に簡単に判断できます。
<webHttp />動作を使用します。
<endpointBehaviors>
<behavior name="My.WcfServices.webHttpBehavior">
<webHttp />
</behavior>
</endpointBehaviors>
Damian Mehers のブログ WCF REST Services で説明されているように、カスタム WebServiceHost とカスタム プロパティ属性を作成します
。Mehers のコードでは、タイプはリクエストのコンテンツ タイプによって決まります。URL を調べるために、.xml、.json、?format=xml|json などのように拡張することもできます。
SerializeReplyメソッドで、URL を調べます。
メッセージ要求 = OperationContext.Current.RequestContext.RequestMessage;
Uri url = request.Properties["OriginalHttpRequestUri"] as Uri;
// ?format クエリ文字列を調べる
System.Collections.Specialized.NameValueCollection colQuery = System.Web.HttpUtility.ParseQueryString(url.Query);
string strResponseFormat = colQuery["format"];
// または拡張
文字列を調べる strResponseFormat = url.LocalPath.Contains(".json") ? "json": "xml";
メソッドを定義する
[OperationContract]
[WebGet(UriTemplate="Hello.{responseFormat}")] // または "Hello?format={responseFormat}"
[DynamicResponseType]
public string Hello(string responseFormat)
{
return "Hello World";
}
URL の例:
http://localhost/myrest.svc/Hello.xml
http://localhost/myrest.svc/Hello.json
または
http://localhost/myrest.svc/Hello?format=xml
http://localhost /myrest.svc/Hello?format=json
- JSON と XML はどちらも、さまざまなブラウザーで簡単に使用できます。JSON 用の jQuery や XML 用の Sarissa などのライブラリを使用すると、さらに簡単になります。
注: 「WebHttpBinding をバインドするエンドポイントのスキーム http に一致するベース アドレスが見つかりませんでした。」というエラーが表示された場合は、baseAddressPrefixFilters要素を追加し、localhost (または任意のドメイン) を IIS ホスト ヘッダー名に追加します。
<system.serviceModel>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true">
<baseAddressPrefixFilters>
<add prefix="http://localhost"/>
</baseAddressPrefixFilters>
</serviceHostingEnvironment>