WCF を 用いて RESTful サービス を作成していると、HTTP レスポンス ヘッダー を任意に変更 ── 場合によっては カスタムヘッダー を追加 ── することで、
クライアント側の処理を対応しやすくしたい場合があるかと思います。
ここでは、HTTP レスポンス ヘッダー を変更する サンプルコード を記載します。
基本的には OutgoingWebResponseContext クラス を利用することで レスポンスヘッダー を変更できるようです。
※ WCF を 用いた RESTful サービス の構築方法 は こちら。
Content-Type の 書き換え
namespace WebService
{
using System.Net;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
public string Greeting(string name)
{
var context = WebOperationContext.Current.OutgoingResponse;
// Content-Type の書き換え
context.ContentType = "text/html";
return "Hello " + name + ".";
}
}
}
ステータス の 書き換え
namespace WebService
{
using System.Net;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
public string Greeting(string name)
{
var context = WebOperationContext.Current.OutgoingResponse;
// ステータス の書き換え
context.StatusCode = HttpStatusCode.Forbidden;
context.StatusDescription = "許可されない操作です。";
return "Hello " + name + ".";
}
}
}
カスタムヘッダー の 追加
namespace WebService
{
using System.Net;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class Service1 : IService1
{
public string Greeting(string name)
{
var context = WebOperationContext.Current.OutgoingResponse;
// カスタム レスポンス ヘッダー の 追記
context.Headers.Add("TEST", "テストヘッダー");
return "Hello " + name + ".";
}
}
}
今回、以下のサイトを参考にしました。
- BRITISH DEVELOPER - WCF REST: How to add a response header
- MSDN - OutgoingWebResponseContext クラス
- try{}catch{}me{} - Adding Custom Message Headers to a WCF Service using Inspectors & Behaviors
- 松崎 剛 Blog - Web Api (REST サービス) の Custom HTTP Header (HTTP ヘッダー)
最後に… このブログに興味を持っていただけた方は、 ぜひ 「Facebookページ に いいね!」または 「Twitter の フォロー」 お願いします!!