3

コンテンツが異なる特定のアクションで (Facebook からのクレジット処理用の) 着信要求があるため、それを処理するための異なるモデル クラスがあります。

これは私の行動です:

public ActionResult Index([ModelBinder(typeof(FacebookCreditModelBinder))] IFacebookRequest facebookRequest)
{
    if (facebookRequest is FacebookPaymentsGetItemsRequest)
    {
        // do whatever
    }
}

そして、これは私のモデル バインダーです。

public class FacebookCreditModelBinder : DefaultModelBinder
{
    public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        var binder = new DefaultModelBinder();
        // how to change the model here in the bindingContext?
        return binder.BindModel(controllerContext, bindingContext); 
    }
}

FacebookPaymentsGetItemsRequestたとえば、着信変数「メソッド」が「payments_get_items」で、if メソッドが「payments_status_update」の場合にオブジェクトを作成したいのですFacebookPaymentsStatusUpdateRequestが、bindingContext でモデルのタイプを変更する方法がわかりません。カスタムモデルバインダーでモデルのタイプを変更することはできますか?


他のアプローチ: BindModel でも試してみましたが、正しいオブジェクトを返すことができましたが、既定のモデル バインダーによって埋められていないため、すべてのプロパティが null です。

public override object BindModel(ControllerContext controllerContext,
        ModelBindingContext bindingContext)
{
    NameValueCollection form = controllerContext.HttpContext.Request.Form;
    if (form.Get("method") == "payments_get_items")
    {
        return new FacebookPaymentsGetItemsRequest();
    }
    ...
4

2 に答える 2

5

あなたはこれを行うことができます:

public class FacebookCreditModelBinder : DefaultModelBinder
{
    protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
    {
        var methodValue = bindingContext.ValueProvider.GetValue("method");
        if (methodValue == null || string.IsNullOrEmpty(methodValue.AttemptedValue))
        {
            throw new Exception("The method parameter was not found");
        }

        var method = methodValue.AttemptedValue;
        IFacebookRequest model = null;
        if (method == "payments_get_items")
        {
            model = FacebookPaymentsGetItemsRequest();
        }
        else if (method == "...")
        {
            model = ....
        }
        else
        {
            throw new NotImplementedException("Unknown method value: " + method);
        }

        bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType());
        return model;
    }
}

に登録しApplication_Startます。

ModelBinders.Binders.Add(typeof(IFacebookRequest), new FacebookCreditModelBinder());

次に、コントローラーのアクションは次のようになります。

public ActionResult Index(IFacebookRequest facebookRequest)
{
    if (facebookRequest is FacebookPaymentsGetItemsRequest)
    {
        // do whatever
    }
}
于 2011-11-26T09:55:53.437 に答える