c# – 自动将实体传递给Controller Action

c# – 自动将实体传递给Controller Action,第1张

概述为模型添加控制器时,生成的 *** 作将如下所示 public ActionResult Edit(int id = 0){ Entity entity = db.Entities.Find(id); if (entity == null) { return HttpNotFound(); } return View(entity);} 现在在我 为模型添加控制器时,生成的 *** 作将如下所示
public ActionResult Edit(int ID = 0){    Entity entity = db.EntitIEs.Find(ID);    if (entity == null)    {        return httpNotFound();    }    return VIEw(entity);}

现在在我的情况下,我采用一个字符串ID,它可以通过多种方式映射到DB ID,生成几行代码以检索正确的实体.将代码复制并粘贴到每个采用ID来检索实体的动作都感觉非常不优雅.

将检索代码放在控制器的私有函数中减少了重复代码的数量,但我仍然留下这个:

var entity = GetEntityByID(ID);if (entity == null)    return httpNotFound();

有没有办法在属性中执行查找并将实体传递给 *** 作?来自python,这可以通过装饰器轻松实现.我设法通过实现IOperationBehavior来为WCF服务做类似的事情,但仍然感觉不那么直截了当.由于通过ID检索实体是您经常需要做的事情,我希望除了复制和粘贴代码之外还有其他方法.

理想情况下,它看起来像这样:

[EntityLookup(ID => db.EntitIEs.Find(ID))]public ActionResult Edit(Entity entity){    return VIEw(entity);}

其中EntityLookup将字符串ID映射到Entity的任意函数,并返回httpNotFound或以检索到的实体作为参数调用该 *** 作.

解决方法 你可以编写一个自定义的ActionFilter:
public class EntityLookupAttribute : ActionFilterattribute{    public overrIDe voID OnActionExecuting(ActionExecutingContext filterContext)    {        // retrIEve the ID parameter from the RouteData        var ID = filterContext.httpContext.Request.RequestContext.RouteData.Values["ID"] as string;        if (ID == null)        {            // There was no ID present in the request,no need to execute the action            filterContext.Result = new httpNotFoundResult();        }        // we've got an ID,let's query the database:        var entity = db.EntitIEs.Find(ID);        if (entity == null)        {            // The entity with the specifIEd ID was not found in the database            filterContext.Result = new httpNotFoundResult();        }        // We found the entity => we Could associate it to the action parameter        // let's first get the name of the action parameter whose type matches        // the entity type we've just found. There should be one and exactly        // one action argument that matches this query,otherwise you have a         // problem with your action signature and we'd better fail quickly here        string paramname = filterContext            .ActionDescriptor            .GetParameters()            .Single(x => x.ParameterType == entity.GetType())            .Parametername;        // and Now let's set its value to the entity        filterContext.ActionParameters[paramname] = entity;    }}

然后:

[EntityLookup]public ActionResult Edit(Entity entity){    // if we got that far the entity was found    return VIEw(entity);}
总结

以上是内存溢出为你收集整理的c# – 自动将实体传递给Controller Action全部内容,希望文章能够帮你解决c# – 自动将实体传递给Controller Action所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1252698.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-07
下一篇 2022-06-07

发表评论

登录后才能评论

评论列表(0条)

保存