gpt4 book ai didi

c# - 是否有任何属性可以避免验证模型?

转载 作者:行者123 更新时间:2023-11-30 22:27:17 25 4
gpt4 key购买 nike

我的 Controller 中有以下操作:

[HttpGet]
public ActionResult Office(GestionOffice model)
{
ModelState.Clear();
model.Initialize();
return View(model);
}

我不需要通过 GET 进行操作,进行验证。这将帮助我执行 GET 调用。

这将是我的理想情况:

[HttpGet]
[NotValidateModel]
public ActionResult Office(GestionOffice model)
{
model.Initialize();
return View(model);
}

谢谢。

编辑

NotValidateModel 阐明了不存在,将归因于大小写以避免验证。

移动模型的原因是MOCK模型

编辑二

我有我的 POST Action ,我需要通过 GET 接收我的 Action ,没有验证的模型,以成功完成 Controller 中 Action 的测试

[HttpGet]
[NotValidateModel]
public ActionResult Office(GestionOffice model)
{
model.Initialize();
return View(model);
}

[HttpPost]
[ActionName("Office")]
[NotValidateModel]
public ActionResult OfficePost(GestionOffice model)
{
if(ModelState.IsValid)
{
model.Save();
return RedirectToAction("List");
}

model.Initialize();
return View(model);
}

@Mark解决方案版

在我看来,我有一些 Action 调用,我必须用 Action 和 Controller 创建一个键。

自定义模型元数据

public class CustomModelMetaData : ModelMetadata
{
public CustomModelMetaData(ModelMetadataProvider provider, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
: base(provider, containerType, modelAccessor, modelType, propertyName)
{
}

public override IEnumerable<ModelValidator> GetValidators(ControllerContext context)
{
var itemKey = this.CreateKey(context.RouteData);
if (context.HttpContext.Items[itemKey] != null && bool.Parse(context.HttpContext.Items[itemKey].ToString()) == true)
{
return Enumerable.Empty<ModelValidator>();
}

return base.GetValidators(context);
}

private string CreateKey(RouteData routeData)
{
var action = (routeData.Values["action"] ?? null).ToString().ToLower();
var controller = (routeData.Values["controller"] ?? null).ToString().ToLower();
return string.Format("NoValidation_{0}_{1}", controller, action);
}
}

过滤器

public class NoValidationAttribute : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
var itemKey = this.CreateKey(filterContext.ActionDescriptor);
filterContext.HttpContext.Items.Add(itemKey, true);
}

private string CreateKey(ActionDescriptor actionDescriptor)
{
var action = actionDescriptor.ActionName.ToLower();
var controller = actionDescriptor.ControllerDescriptor.ControllerName.ToLower();
return string.Format("NoValidation_{0}_{1}", controller, action);
}
}

编辑过滤器

可能会出现这样的情况,在主视图中有一个foreach来调用属性为NoValidation的几个分部 View 。在本例中,包括一个检查 key 的控件。由于在key中包含了controller的名字和action,这个key几乎是唯一的,只能在描述的情况下重复

public class NoValidationAttribute : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
var itemKey = this.CreateKey(filterContext.ActionDescriptor);
if (!filterContext.HttpContext.Items.Contains(itemKey))
{
filterContext.HttpContext.Items.Add(itemKey, true);
}
}

private string CreateKey(ActionDescriptor actionDescriptor)
{
var action = actionDescriptor.ActionName.ToLower();
var controller = actionDescriptor.ControllerDescriptor.ControllerName.ToLower();
return string.Format("NoValidation_{0}_{1}", controller, action);
}
}

最佳答案

[查看下面的更新以及@ANDRES 在问题中提到的编辑]

您尝试做的事情并不难实现,我不确定您为什么要这么做。我试图通过自定义 ModelMetaData 和过滤器(未完全测试)来完成。

我们无法从模型绑定(bind)器或元数据提供程序中读取装饰在操作上的属性,因此我们需要一个过滤器。过滤器在 HttpContext.Items 中放置了一些值,我们可以从自定义元数据提供程序 (http://stackoverflow.com/questions/6198155/asp-net-mvc-modelbinder -getting-action-method).

过滤器

public class NoValidationAttribute : FilterAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
// please see the edits in question to see the key generation
filterContext.HttpContext.Items.Add("NoValidation", true);
}
}

自定义模型元数据

public class CustomModelMetaData : ModelMetadata
{
public CustomModelMetaData(ModelMetadataProvider provider, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName) :
base(provider, containerType, modelAccessor, modelType, propertyName)
{
}

public override System.Collections.Generic.IEnumerable<ModelValidator> GetValidators(ControllerContext context)
{
if (context.HttpContext.Items["NoValidation"] != null && bool.Parse(context.HttpContext.Items["NoValidation"].ToString()) == true)
return Enumerable.Empty<ModelValidator>();

return base.GetValidators(context);
}
}

自定义模型元数据提供者

public class CustomModelMetaDataProvider : DataAnnotationsModelMetadataProvider
{
protected override ModelMetadata CreateMetadata(System.Collections.Generic.IEnumerable<Attribute> attributes,
Type containerType, Func<object> modelAccessor,
Type modelType,
string propertyName)
{
return new CustomModelMetaData(this, containerType, modelAccessor, modelType,
propertyName);
}
}

Global.asax.cs

ModelMetadataProviders.Current = new CustomModelMetaDataProvider();

用法

[HttpGet]
[NoValidation]
public ActionResult Office(GestionOffice model)
{
...
}

=================================更新 ====== ===============================

与其通过继承 ModelMetadata 创建 CustomModelMetaData,我认为继承 DataAnnotationsModelMetadata 会更好。

public class CustomModelMetaData : DataAnnotationsModelMetadata
{
public CustomModelMetaData(DataAnnotationsModelMetadataProvider provider, Type containerType,
Func<object> modelAccessor, Type modelType, string propertyName,
DisplayColumnAttribute displayColumnAttribute) :
base(provider, containerType, modelAccessor, modelType, propertyName, displayColumnAttribute)
{
}

public override IEnumerable<ModelValidator> GetValidators(ControllerContext context)
{
var itemKey = this.CreateKey(context.RouteData);

if (context.HttpContext.Items[itemKey] != null &&
bool.Parse(context.HttpContext.Items[itemKey].ToString()) == true)
{
return Enumerable.Empty<ModelValidator>();
}

return base.GetValidators(context);
}

private string CreateKey(RouteData routeData)
{
var action = (routeData.Values["action"] ?? null).ToString().ToLower();
var controller = (routeData.Values["controller"] ?? null).ToString().ToLower();
return string.Format("NoValidation_{0}_{1}", controller, action);
}
}

CustomModelMetaDataProvider 中,您必须设置一些属性。

public class CustomModelMetaDataProvider : DataAnnotationsModelMetadataProvider
{
protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes,
Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
{
var displayColumnAttribute = new List<Attribute>(attributes).OfType<DisplayColumnAttribute>().FirstOrDefault();

var baseMetaData = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);

// is there any other good strategy to copy the properties?
return new CustomModelMetaData(this, containerType, modelAccessor, modelType, propertyName, displayColumnAttribute)
{
TemplateHint = baseMetaData.TemplateHint,
HideSurroundingHtml = baseMetaData.HideSurroundingHtml,
DataTypeName = baseMetaData.DataTypeName,
IsReadOnly = baseMetaData.IsReadOnly,
NullDisplayText = baseMetaData.NullDisplayText,
DisplayFormatString = baseMetaData.DisplayFormatString,
ConvertEmptyStringToNull = baseMetaData.ConvertEmptyStringToNull,
EditFormatString = baseMetaData.EditFormatString,
ShowForDisplay = baseMetaData.ShowForDisplay,
ShowForEdit = baseMetaData.ShowForEdit,
Description = baseMetaData.Description,
ShortDisplayName = baseMetaData.ShortDisplayName,
Watermark = baseMetaData.Watermark,
Order = baseMetaData.Order,
DisplayName = baseMetaData.DisplayName,
IsRequired = baseMetaData.IsRequired
};
}
}

关于c# - 是否有任何属性可以避免验证模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11367853/

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