从WebApi模型绑定器中的动态数据创建静态模型
本文关键字:模型 动态 数据 创建 静态 WebApi 绑定 | 更新日期: 2023-09-27 18:13:58
我有我的POST
方法,我用它来触发发送电子邮件
[HttpPost]
public HttpResponseMessage Post(IEmail model)
{
SendAnEmailPlease(model);
}
我有很多类型的电子邮件要发送,所以我抽象到一个接口,所以我只需要一个post方法
config.BindParameter(typeof(IEmail), new EmailModelBinder());
我有模型绑定器点击fine
public class EmailModelBinder : IModelBinder
{
public bool BindModel(
HttpActionContext actionContext,
ModelBindingContext bindingContext )
{
// Logic here
return false;
}
}
我正在努力将bindingContext.PropertyMetadata
转换为我的电子邮件poco之一的逻辑
public IDictionary<string, ModelMetadata> PropertyMetadata { get; }
在PropertyMetadata中,我将对象类型作为字符串传递,我认为我可以用Activator.CreateInstance
方法创建一个类。
eg: EmailType = MyProject.Models.Email.AccountVerificationEmail
有简单的方法来完成这个吗?
相关问题
- ASP。通用类型的。NET Web API模型绑定器
这是我想到的解决方案,可能对其他人有用。
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;
}
}