加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 05:38:07 所属栏目:百科 来源:网络整理
导读:为模型添加控制器时,生成的操作将如下所示 public ActionResult Edit(int id = 0){ Entity entity = db.Entities.Find(id); if (entity == null) { return HttpNotFound(); } return View(entity);} 现在在我的情况下,我采用一个字符串id,它可以通过多种方式
为模型添加控制器时,生成的操作将如下所示
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);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读