系统的通用GET web api端点.类型和Id



我在net 7中使用web api。是否有办法使绑定引擎理解Typeobjectid参数?

我有一个端点,我想重用它来通过id获取特定类型的实体。

在一个动作中不支持泛型类型,所以我想我需要的是这样的东西:

[HttpGet("{id}")]
public object Get(Type type, object id) 
{
// call _entityFrameWorkDatabaseContext.Find(Type type, object id)
}

我想用/theAction/1?type=<AssemblyQualifiedName>之类的东西来调用它。这可能吗?

自定义模型绑定器应该能够得到您所需要的。

public class TypeEntityBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
var modelName = bindingContext.ModelName;
// Try to fetch the value of the argument by name
var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName);
if (valueProviderResult == ValueProviderResult.None)
{
return Task.CompletedTask;
}
bindingContext.ModelState.SetModelValue(modelName, valueProviderResult);
var value = valueProviderResult.FirstValue;
// Check if the argument value is null or empty
if (string.IsNullOrEmpty(value))
{
return Task.CompletedTask;
}
// Treat it like a string request parameter
if (!string.TryParse(value, out var type))
{
bindingContext.ModelState.TryAddModelError(
modelName, "Type must be a string.");
return Task.CompletedTask;
}
// In a debugging session, make sure the `type` is binding correctly
// Make sure the assembly name is correct and matches a real type
var model = Type.GetType($"namespace.{type}, assemblyName");
// Bind the result to Type
bindingContext.Result = ModelBindingResult.Success(model);
return Task.CompletedTask;  // <-- run for the hills!
}
}

然后,简单地设置属性以激活自定义绑定器。

Get([ModelBinder(BinderType = typeof(TypeEntityBinder))] Type type, object id) 

请记住,这主要是理论代码。您可能遇到的一个问题是,自定义绑定器没有在请求管道中正确注册,因此请确保实际包含了它。另外,通过调试技术检查type变量的内容。

https://learn.microsoft.com/en us/aspnet/core/mvc/advanced/custom -模型- binding?view=aspnetcore - 7.0

您可以通过获取类型作为字符串并使用反射来获取对象type来做到这一点,您可以在这里阅读更多关于反射的内容。

[HttpGet("{id}")]
public object Get(string type, int id) 
{
var type = Type.GetType($"namespace.{type}, assemblyName");

// you can add a validator here to make sure that type is valid.
if(type == null)
{
// your code goes here
}
// here you retrieve the data from DB using ef.
var entity = _entityFrameWorkDatabaseContext.Find(type, id);

// you can check if the entity is null and do what you want
if(entity == null)
{
// your code goes here
}
return entity;
}
  1. 尝试使用反射获取实体。
  2. 如果获得实体类型成功调用_entityFrameWorkDatabaseContext类型和Id (int/string/etc..)
  3. 返回实体。

您可以通过以下方式调用端点

GET <address>/{id}?type=<your-type>