3

最近リリースされたMVC4Beta(4.0.20126.16343)を使用しており、アレイで機能しない逆シリアル化/モデルバインディングに関する既知の問題の回避に取り組んでいます(ここでスタックオーバーフローを参照)

明示的なカスタムバインディングを接続するのに問題があります。カスタムIModelBinderを登録しました(または登録しようとしました)が、postアクションが呼び出されても、カスタムバインダーはヒットせず、デフォルトのシリアル化を取得します(null配列を使用-wiresharkは、着信する複雑なオブジェクトに配列要素が含まれていることを示していますが) )。

何かが足りないような気がします。解決策や洞察をいただければ幸いです。

ありがとう。

global.asax.csから:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

protected void Application_Start()
{
    ModelBinders.Binders.Add(typeof(DocuSignEnvelopeInformation), new DocusignModelBinder());
    AreaRegistration.RegisterAllAreas();

    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);

    BundleTable.Bundles.RegisterTemplateBundles();
}

と私のカスタムバインダー:

public object BindModel(ControllerContext controllerContext, System.Web.Mvc.ModelBindingContext bindingContext)
{
    var value = bindingContext.ValueProvider.GetValue("envelope");

    var model = new DocuSignEnvelopeInformation();

    //build out the complex type here

    return model;
}

そして私のコントローラーはただ:

public void Post(DocuSignEnvelopeInformation envelope)
{
    Debug.WriteLine(envelope);
}
4

2 に答える 2

2

通常、モデルバインダーはDIコンテナーを介して登録し、機能します。DependencyResolverによって使用されるDIコンテナーにIModelBinderProviderを登録し、そこからGetBinderメソッドでModelBinderを返します。

于 2012-05-18T19:33:03.967 に答える
1

これが私がやったことです(ASP.NET MVC3のモデルバインディングXMLのJimmyBogardに感謝します)

ソリューションをMVC3に戻しました(リリース前の不安によって再び燃えました)

ModelBinderProviderを追加しました:

public class XmlModelBinderProvider : IModelBinderProvider
{
    public IModelBinder GetBinder(Type modelType)
    {
        var contentType = HttpContext.Current.Request.ContentType;

        if (string.Compare(contentType, @"text/xml",
            StringComparison.OrdinalIgnoreCase) != 0)
        {
            return null;
        }

        return new XmlModelBinder();
    }
}

およびModelBinder

public class XmlModelBinder : IModelBinder
{
    public object BindModel(
        ControllerContext controllerContext,
        ModelBindingContext bindingContext)
    {
        var modelType = bindingContext.ModelType;
        var serializer = new XmlSerializer(modelType);

        var inputStream = controllerContext.HttpContext.Request.InputStream;

        return serializer.Deserialize(inputStream);
    }
}

そしてこれをApplication_Start()に追加しました:

    ModelBinderProviders.BinderProviders
    .Add(new XmlModelBinderProvider());

私のコントローラーは質問とまったく同じままでした。

御馳走のように動作します。新しい「文字列なし」アプローチがMVC4で適切に到着した場合は素晴らしいでしょうが、この逆シリアル化への手動バインディングアプローチは必ずしも面倒ではありません。

于 2012-05-22T13:11:45.887 に答える