【发布时间】:2021-02-25 17:29:15
【问题描述】:
我的要求是只允许在 OData $filter 选项中使用几个属性。这里我有一个学生模型,其中包含一堆属性。我只希望“名称”属性启用 $filter 功能。但不知何故,它不起作用。谁能帮帮我。
以下是我的代码
我的模特:
公开课学生 {
public string Id { get; set; }
public string Name { get; set; }
public string AccessType { get; set; }
public string SortOrder { get; set; }
public string Status { get; set; }
}
我的查询验证器:
public class RestrictiveFilterByQueryValidator : FilterQueryValidator
{
static readonly string[] allowedProperties = { "name" };
public RestrictiveFilterByQueryValidator(DefaultQuerySettings defaultQuerySettings)
: base(defaultQuerySettings)
{
}
public override void ValidateSingleValuePropertyAccessNode(
SingleValuePropertyAccessNode propertyAccessNode,
ODataValidationSettings settings)
{
string propertyName = null;
if (propertyAccessNode != null)
{
propertyName = propertyAccessNode.Property.Name;
}
if (propertyName != null && !allowedProperties.Contains(propertyName))
{
throw new ODataException(
String.Format("Filter on {0} not allowed", propertyName));
}
base.ValidateSingleValuePropertyAccessNode(propertyAccessNode, settings);
}
public static implicit operator System.Web.Http.OData.Query.Validators.FilterQueryValidator(RestrictiveFilterByQueryValidator v)
{
throw new NotImplementedException();
}
}
我的自定义可查询属性:
public class MyQueryableAttribute : QueryableAttribute
{
public override void ValidateQuery(HttpRequestMessage request, System.Web.Http.OData.Query.ODataQueryOptions queryOptions)
{
if (queryOptions.Filter != null)
{
queryOptions.Filter.Validator = new RestrictiveFilterByQueryValidator(new DefaultQuerySettings());
}
// HttpRequestMessage request, ODataQueryOptions queryOptions
base.ValidateQuery(request, queryOptions);
}
}
最后是我的 API 控制器方法:
[MyQueryable]
public ActionResult<IEnumerable<Student>> GetAllStudent()
{
}
当我按照上面的代码进行操作时,具有有效属性的正常 $filter 也无法按预期工作。我想我错过了一些东西。任何帮助将不胜感激。
【问题讨论】: