gpt4 book ai didi

asp.net-mvc-3 - RemoteAttribute 验证器不会触发服务器端

转载 作者:行者123 更新时间:2023-12-01 01:30:04 25 4
gpt4 key购买 nike

似乎 ASP.NET MVC 3 中引入的 RemoteAttribute 验证器不会在服务器端进行验证,只能通过 JavaScript 进行验证。如果您在浏览器中关闭 JS,您会发现在模型绑定(bind)上,验证 Controller 操作(您在使用 RemoteAttribute 装饰模型属性时指定)将不会被命中。事实上,如果您检查 RemoteAttribute 的源代码,您会发现 IsValid 方法在所有情况下都只返回 true。

这似乎是一个很大的遗漏——我认为大多数人会认为 RemoteAttribute 会像所有其他内置验证器一样工作,并在客户端和服务器端进行验证。相反,您必须在 Controller 操作中手动调用远程验证逻辑。

人们是否意识到这一点,是否有人试图解决这个问题?

我将 RemoteAttribute 子类化并覆盖了 IsValid 方法,在该方法中我可以访问 RouteData、RouteName 和 Routes 以及返回操作 URL 的 GetUrl 方法。我正在考虑使用反射来调用 Action 并获得结果,以便我可以查看它是否有效,但是是否有任何内置方法可以在不诉诸反射的情况下使用?

最佳答案

也许它不是最好的代码。如果您有一些建议,请告诉我。
开发@MVC4

具有自定义属性的模型属性

[CustomRemote("ValidateIP", "Validation", ErrorMessage = "Input is not a valid IP")]

子类 RemoteAttribute
/// <summary>
/// Custom Remote Attribute for Client an Server validation.
/// </summary>
public class CustomRemoteAttribute : RemoteAttribute
{
/// <summary>
/// List of all Controllers on MVC Application
/// </summary>
/// <returns></returns>
private static List<Type> GetControllerList()
{
return Assembly.GetCallingAssembly().GetTypes().Where(type => type.IsSubclassOf(typeof(Controller))).ToList();
}

/// <summary>
/// Constructor of base class.
/// </summary>
protected CustomRemoteAttribute()
{
}

/// <summary>
/// Constructor of base class.
/// </summary>
public CustomRemoteAttribute(string routeName)
: base(routeName)
{
}

/// <summary>
/// Constructor of base class.
/// </summary>
public CustomRemoteAttribute(string action, string controller)
: base(action, controller)
{
}

/// <summary>
/// Constructor of base class.
/// </summary>
public CustomRemoteAttribute(string action, string controller, string areaName)
: base(action, controller, areaName)
{
}

/// <summary>
/// Overridden IsValid function
/// </summary>
/// <param name="value"></param>
/// <param name="validationContext"></param>
/// <returns></returns>
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// Find the controller passed in constructor
var controller = GetControllerList().FirstOrDefault(x => x.Name == string.Format("{0}Controller", this.RouteData["controller"]));
if (controller == null)
{
// Default behavior of IsValid when no controller is found.
return ValidationResult.Success;
}

// Find the Method passed in constructor
var mi = controller.GetMethod(this.RouteData["action"].ToString());
if (mi == null)
{
// Default behavior of IsValid when action not found
return ValidationResult.Success;
}

// Create instance of the controller to be able to call non static validation method
var instance = Activator.CreateInstance(controller);

// invoke the method on the controller with value
var result = (JsonResult)mi.Invoke(instance, new object[] { value });

// Return success or the error message string from CustomRemoteAttribute
return (bool) result.Data ? ValidationResult.Success : new ValidationResult(base.ErrorMessageString);
}
}

验证 Controller 代码
/// <summary>
/// Controller for Client and Server validation
/// <remarks>disable OutputCache</remarks>
/// </summary>
[OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
public class ValidationController : Controller
{
/// <summary>
/// !!!!!!!!!!!!!!!!!! Needed for instance creation in custom attribute !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
/// </summary>
public ValidationController()
{
}

/// <summary>
/// IP regex pattern of my choice
/// </summary>
const string IpPattern = @"^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$";

/// <summary>
/// MAC regex pattern of my choice
/// </summary>
const string MacPattern = "^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$";

/// <summary>
/// Validate IP
/// </summary>
/// <param name="ip">IP param is only submited on Serverside validation!!!</param>
/// <returns>Validation Result</returns>
public JsonResult ValidateIP(string ip)
{
// Check if ip and httpcontext is null to dodge NullReferenceException on Server side validation
if (string.IsNullOrEmpty(ip) && HttpContext == null)
{
return Json(false, JsonRequestBehavior.AllowGet);
}

/* Use IP on Serverside validation
* Use Querystring Param 0 to get IP from Client side vaildation without the need for the correct Id of input control */
string checkip = string.IsNullOrEmpty(ip) ? HttpContext.Request.QueryString[0] : ip;
if (string.IsNullOrEmpty(checkip))
{
return new JsonResult { Data = true, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}

return new JsonResult
{
Data = Regex.IsMatch(checkip, IpPattern),
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
}

关于asp.net-mvc-3 - RemoteAttribute 验证器不会触发服务器端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5393020/

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