0

目标是创建一个 ActionFilter 来自动保存所有联系人。

代码:

视图模型

Origem用于标识已保存联系人的视图来源(本例中只有两个视图 contatoContatoViewModel和 Careers 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是一个对象。如何从对象隐式转换?

谢谢。

4

1 回答 1

1

异常肯定是由于您调用转换的类型是object.

您也不能从基本object类型创建隐式转换。在能够使用隐式转换器之前,您需要转换为正确的类型。

我不喜欢使用隐式/显式转换运算符。我更喜欢像 AutoMapper 这样的 propper 映射解决方案。

于 2013-04-02T15:34:41.237 回答