2013-05-17 73 views
0

我有我的POST方法,我用它來觸發電子郵件的發送在的WebAPI模型綁定創建從動態數據的靜態模型

[HttpPost] 
public HttpResponseMessage Post(IEmail model) 
{ 
    SendAnEmailPlease(model); 
} 

我有很多類型的電子郵件的發送,所以我抽象客場接口,所以我只需要一個POST方法

config.BindParameter(typeof(IEmail), new EmailModelBinder()); 

我有被擊中罰款我的模型綁定

public class EmailModelBinder : IModelBinder 
{ 
    public bool BindModel(
     HttpActionContext actionContext, 
     ModelBindingContext bindingContext) 
    { 
     // Logic here   

     return false; 
    } 
} 

我與邏輯掙扎轉動bindingContext.PropertyMetadata到我的郵箱之一波蘇斯

public IDictionary<string, ModelMetadata> PropertyMetadata { get; }  

在PropertyMetadata我傳遞的對象類型爲字符串,我想我可以用它來創建一個類Activator.CreateInstance方法。

eg: EmailType = MyProject.Models.Email.AccountVerificationEmail 

有沒有簡單的方法來實現這個目標?


相關問題

回答

0

這是我想出瞭解決辦法,可能是別人在那裏有用。

public class EmailModelBinder : IModelBinder 
{ 
    public bool BindModel(
     HttpActionContext actionContext, 
     ModelBindingContext bindingContext) 
    { 
     string body = actionContext.Request.Content 
         .ReadAsStringAsync().Result; 

     Dictionary<string, string> values = 
      JsonConvert.DeserializeObject<Dictionary<string, string>>(body); 

     var entity = Activator.CreateInstance(
      typeof(IEmail).Assembly.FullName, 
      values.FirstOrDefault(x => x.Key == "ObjectType").Value 
      ).Unwrap(); 

     JsonConvert.PopulateObject(body, entity); 

     bindingContext.Model = (IEmail)entity; 

     return true; 
    } 
}