EnsurePresenseOfAttribute

這是我建立的一個屬性示例,用於驗證在 POST 路由中接收的請求物件中是否已分配所需引數。我決定採用這種方法,因為標準的 ModelState.IsValid 方法無效。這是因為所需屬性根據呼叫的操作而有所不同。

// ATTRIBUTE 僅對方法有效[AttributeUsage(AttributeTargets.Method)] // INHERIT ActionFilterAttribute public class EnsurePresencesOfAttribute:ActionFilterAttribute {// ReSharper 禁用一次 InconsistentNaming 需要公共字串{get; 組; }

// VALIDATE REQUIRED ATTRIBUTES
// FOR NON-ASYNC REQUESTS
public override void OnActionExecuting(HttpActionContext context)
{
    Dictionary<string, object> model = context.ActionArguments;
    var serialstring = JsonConvert.SerializeObject(model);
    foreach (var requirement in required.Split(','))
    {
        if (serialstring.Contains($"{requirement}\":null"))
        {
            ValueError(context, requirement);
            return;
        }
    }
    base.OnActionExecuting(context);
}

// VALIDATE THE REQUIRED ATTRIBUTES ARE PRESENT
// FOR ASYNC REQUESTS
public override Task OnActionExecutingAsync(HttpActionContext context, CancellationToken token)
{
    Dictionary<string, object> model = context.ActionArguments;
    var serialstring = JsonConvert.SerializeObject(model);
    foreach (var requirement in required.Split(','))
    {
        if (serialstring.Contains($"{requirement}\":null"))
        {
            ValueError(context, requirement);
            return Task.FromResult(0);
        }
    }
    return base.OnActionExecutingAsync(context, token);
}

// LOG ERROR AND RETURN AND SET ERROR RESPONSE
private static void ValueError(HttpActionContext context, string requirement)
{
    var action = context.ActionDescriptor.ActionName;
    AppUtils.LogError($"{action} Failed : Missing Required Attribute {requirement}. ");
    using (var controller = new BaseApiController { Request = new HttpRequestMessage() })
    {
        controller.Request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration());
        context.Response = controller.InvalidInputResponse();
    }
}