gpt4 book ai didi

c# - 自动将实体传递给 Controller ​​操作

转载 作者:太空狗 更新时间:2023-10-29 23:32:36 26 4
gpt4 key购买 nike

为模型添加 Controller 时,生成的操作看起来像这样

public ActionResult Edit(int id = 0)
{
Entity entity = db.Entities.Find(id);
if (entity == null)
{
return HttpNotFound();
}
return View(entity);
}

现在,在我的例子中,我采用了一个可以通过多种方式映射到数据库 ID 的字符串 ID,生成几行代码来检索正确的实体。将该代码复制并粘贴到每个需要 id 来检索实体的操作感觉非常不雅。

将检索代码放在 Controller 的私有(private)函数中可以减少重复代码的数量,但我仍然需要这样做:

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 采用任意函数将 string 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 ​​操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15069881/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com