目标是创建一个ActionFilter来自动保存所有联系人。
的ViewModels
Origem
用于标识已保存联系人的观看来源(在这种情况下,只有两个观看次约ContatoViewModel
和职业TrabalheConoscoViewModel
)
public class ContatoViewModel
{
public string Nome { get; set; }
public string Email { get; set; }
public string Assunto { get; set; }
public string Mensagem { get; set; }
public static explicit operator Contato(ContatoViewModel vm)
{
return new Contato { Nome = vm.Nome, Email = vm.Email, PrimeiroContato = DateTime.Now, Origem = OrigemContato.Contato };
}
}
public class TrabalheConoscoViewModel
{
public string Nome { get; set; }
public string Email { get; set; }
public string Mensagem { get; set; }
public HttpPostedFileBase Arquivo { get; set; }
public static explicit operator Contato(TrabalheConoscoViewModel vm)
{
return new Contato{ Nome = vm.Nome, Email = vm.Email, PrimeiroContato=DateTime.Now, Origem = OrigemContato.Candidato };
}
}
过滤
public class LogContatoAttribute : ActionFilterAttribute
{
private readonly string _paramName;
private object _paramValue = null;
public LogContatoAttribute(string paramName = "vm")
{
_paramName = paramName;
}
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.ActionParameters.ContainsKey(_paramName))
_paramValue = filterContext.ActionParameters[_paramName];
else
throw new ArgumentException("Parâmetro não encontrado.", _paramName);
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
var a = (Contato)_paramValue; //Error!!!!
// Save in database
}
}
动作
public ActionResult contato()
{
return View(new ContatoViewModel());
}
[HttpPost]
[ValidateAntiForgeryToken]
[LogContato("vm")]
public ActionResult contato(ContatoViewModel vm)
{
if (ModelState.IsValid)
{
new mailController().contato(vm).Deliver();
return RedirectToRoute("Default", new RouteValueDictionary { { "controller", "home" }, { "action", "contato" } });
}
ModelState.AddModelError("", "Não foi possível enviar sua mensagem.");
return View(vm);
}
System.InvalidCastException was unhandled by user code
HResult=-2147467262
Message=Unable to cast object of type 'CreditoImobiliarioBB.WebSite.ViewModels.ContatoViewModel' to type 'CreditoImobiliarioBB.WebSite.Models.Contato'.
Source=CreditoImobiliarioBB.WebSite
StackTrace:
at CreditoImobiliarioBB.WebSite.Infra.Filters.LogContatoAttribute.OnActionExecuted(ActionExecutedContext filterContext) in w:\Clients\creditoimobiliariobb\website\src\CreditoImobiliarioBB.WebSite\Infra\Filters\LogContato.cs:line 27
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49()
InnerException:
我相信这是因为_paramValue
是一个对象。
如何从对象隐式转换?
感谢。
答案 0 :(得分:1)
异常肯定是因为您调用转换的类型是object
。
您也无法从基本object
类型创建隐式转化。在能够使用隐式转换器之前,您需要转换为正确的类型。
我不是使用隐式/显式转换运算符的忠实粉丝。我更喜欢像AutoMapper这样的propper映射解决方案。