实际上,我有一个使用WebService检索某些客户端信息的应用程序。
所以我正在验证我的ActionResult内部的登录信息,例如:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ClientLogin(FormCollection collection)
{
if(Client.validate(collection["username"], collection["password"]))
{
Session["username"] = collection["username"];
Session["password"] = collection["password"];
return View("valid");
}
else
{
Session["username"] = "";
Session["password"] = "";
return View("invalid");
}
}
其中Client.Validate()是一种基于POST用户名和密码提供的信息返回 bool 值的方法
但是我改变了主意,我想在该方法的开头使用该不错的ActionFilterAttributes,以便仅在Client.validate()返回true时才呈现它,与[Authorize]相同,但使用我的自定义网络服务,因此我会有类似的东西:
[AcceptVerbs(HttpVerbs.Post)]
[ValidateAsClient(username=postedUsername,password=postedPassword)]
//Pass Posted username and password to ValidateAsClient Class
//If returns true render the view
public ActionResult ClientLogin()
{
return View('valid')
}
然后在ValidateAsClient中,我将得到以下内容:
public class ValidateAsClient : ActionFilterAttribute
{
public string username { get; set; }
public string password { get; set; }
public Boolean ValidateAsClient()
{
return Client.validate(username,password);
}
}
所以我的问题是,我不确切地知道如何使它工作,因为我不知道如何将POSTED信息传递给[ValidateAsClient(username = postedUsername,password = postedPassword)],而且我该如何使函数ValidateAsClient是否正常工作?
我希望这很容易理解
提前致谢
最佳答案
大概是这样的:
[AttributeUsage(AttributeTargets.All)]
public sealed class ValidateAsClientAttribute : ActionFilterAttribute
{
private readonly NameValueCollection formData;
public NameValueCollection FormData{ get { return formData; } }
public ValidateAsClientAttribute (NameValueCollection formData)
{
this.formData = formData;
}
public override void OnActionExecuting
(ActionExecutingContext filterContext)
{
string username = formData["username"];
if (string.IsNullOrEmpty(username))
{
filterContext.Controller.ViewData.ModelState.AddModelError("username");
}
// you get the idea
}
}
并像这样使用它:
[ValidateAsClient(HttpContext.Request.Form)]