Asp.net-Mvc-4

ASP.NET Web API - 模型綁定器

  • November 28, 2019

我需要使用某種自定義模型綁定器來始終處理英國格式的傳入日期,我已經設置了一個自定義模型綁定器並像這樣註冊:

GlobalConfiguration.Configuration.BindParameter(typeof(DateTime), new DateTimeModelBinder());

這似乎僅適用於查詢字元串參數,並且僅在我指定時才有效

$$ ModelBinder $$在我的參數上,有沒有辦法讓所有動作都使用我的模型綁定器:

public IList<LeadsLeadRowViewModel> Get([ModelBinder]LeadsIndexViewModel inputModel)

另外,我怎樣才能將我發布的表單發送到我的 Api 控制器以使用我的模型綁定器?

我認為您不需要模型活頁夾。你的方法不正確。日期的正確方法是使用客戶端全球化庫(如globalize 庫)來解析以任何語言格式化的日期並將它們轉換為 JavaScript 日期對象。然後,您可以使用瀏覽器以 JSON 格式序列化您的數據腳本資料結構JSON.stringify,這應該可以。最好始終使用標準格式的日期並使用格式化程序而不是模型活頁夾。如果您使用 C# DateTime 對象的kind參數來指定日期時間是以本地時間還是以 UTC 時間表示,可用的格式化程序也可以正確處理 TimeZones 。

您可以通過實現 ModelBinderProvider 並將其插入服務列表來全域註冊模型綁定器。

Global.asax 中的使用範例:

GlobalConfiguration.Configuration.Services.Insert(typeof(ModelBinderProvider), 0, new Core.Api.ModelBinders.DateTimeModelBinderProvider());

下面是展示 ModelBinderProvider 和 ModelProvider 實現的範常式式碼,它以文化感知方式(使用目前執行緒文化)轉換 DateTime 參數;

DateTimeModelBinderProvider 實現:

using System;
using System.Web.Http;
using System.Web.Http.ModelBinding;

public class DateTimeModelBinderProvider : ModelBinderProvider
{
   readonly DateTimeModelBinder binder = new DateTimeModelBinder();

   public override IModelBinder GetBinder(HttpConfiguration configuration, Type modelType)
   {
       if (DateTimeModelBinder.CanBindType(modelType))
       {
           return binder;
       }

       return null; 
   }
}

DateTimeModelBinder 實現:

public class DateTimeModelBinder : IModelBinder
{
   public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
   {
       ValidateBindingContext(bindingContext);

       if (!bindingContext.ValueProvider.ContainsPrefix(bindingContext.ModelName) ||
           !CanBindType(bindingContext.ModelType))
       {
           return false;
       }

       bindingContext.Model = bindingContext.ValueProvider
           .GetValue(bindingContext.ModelName)
           .ConvertTo(bindingContext.ModelType, Thread.CurrentThread.CurrentCulture);

       bindingContext.ValidationNode.ValidateAllProperties = true;

       return true;
   }

   private static void ValidateBindingContext(ModelBindingContext bindingContext)
   {
       if (bindingContext == null)
       {
           throw new ArgumentNullException("bindingContext");
       }

       if (bindingContext.ModelMetadata == null)
       {
           throw new ArgumentException("ModelMetadata cannot be null", "bindingContext");
       }
   }

   public static bool CanBindType(Type modelType)
   {
       return modelType == typeof(DateTime) || modelType == typeof(DateTime?);
   }
}

引用自:https://stackoverflow.com/questions/12246254