カスタム モデル バインダーに代わるより良い方法はありません。他の誰かがこれを見た場合に備えて、バインダーの実装をここに投稿します。モデル バインダーを使用すると、Accept ヘッダーをアクションの直接入力に強くバインドできるため、戻り値の型を直接テストでき、人為的に必要以上のアクションを強制することも、動的に型指定されたビューデータにつながることもありません。 /バッグ。
サポートされている列挙型を持つモデル バインダーを次に示します。
public enum RequestAcceptType
{
NotSpecified,
Json,
Xml
}
public class RequestAcceptTypeModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException("bindingContext");
}
RequestAcceptType acceptType = RequestAcceptType.NotSpecified;
// Try for Json
if (controllerContext.HttpContext.Request.AcceptTypes.Contains("application/json") || controllerContext.HttpContext.Request.Url.Query.Contains("application/json"))
{
acceptType = RequestAcceptType.Json;
}
// Default to Xml
if (acceptType == RequestAcceptType.NotSpecified)
{
acceptType = RequestAcceptType.Xml;
}
return acceptType;
}
}
Application_Start メソッドの Global.asax の関連ビットを次に示します。
ModelBinders.Binders[typeof(RequestAcceptType)] = new RequestAcceptTypeModelBinder();
次に、アクションで使用するには、列挙型で引数 (任意の名前) を作成します。
public ActionResult Index(RequestAcceptType acceptType)
数日以内に誰もより良い方法で応答しない場合は、これを答えとして受け入れます.