ASP.NET MVC- 게시물 데이터를 검증하기위한 ActionFilterAttribute
-
05-07-2019 - |
문제
실제로 웹 서비스를 사용하여 일부 클라이언트 정보를 검색하는 응용 프로그램이 있습니다. 그래서 나는 다음과 같은 내용의 로그인 정보를 확인하고있었습니다.
[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 ()는 게시물 사용자 이름 및 비밀번호에 제공된 정보를 기반으로 부울을 반환하는 메소드입니다.
그러나 나는 내 마음을 바꾸었고 메소드의 시작 부분에서 그 멋진 actionfilterattributes를 사용하고 싶습니다. client.validate ()가 true를 반환하면 [승인]과 동일하지만 내 사용자 정의 웹 서비스를 사용하면 렌더링됩니다. 나는 다음과 같은 것을 가질 것입니다.
[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);
}
}
그래서 내 문제는 게시 된 정보를 ValidAteAsclient (username = postedUsername, password = postedpassword) 또한 기능을 유효한 기능을 올바르게 작동시킬 수있는 방법은 무엇입니까?
나는 이것이 이해하기 쉽기를 바랍니다. 미리 감사드립니다
해결책
아마도 다음과 같은 것 :
[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)]
다른 팁
다음 방법을 무시해야합니다.
public override void OnActionExecuting(ActionExecutingContext context)
컨텍스트 객체에서 게시물 데이터에 액세스하십시오.
나는 사용하는 것이 좋은 생각이라고 생각하지 않습니다. ActionFilterAttribute
이 경우. 그리고 당신이하고 싶은 것은 확실히 동일하지 않습니다. Authorize
속성.
그만큼 Authorize
속성은 공통 논리를 컨트롤러/동작에 주입합니다. 그것은 :
사용자가 로그인되지 않은 경우 로그인 페이지로 리디렉션됩니다. 그렇지 않으면 작업을 실행하도록합니다.
당신의 ClientLogin
행동은 현재해야 할 일을합니다.
그 논리를 ActionFilterAttribute
.
ASP.NET MVC의 사용자 정의 바인더 로이 문제를 해결합니다.
귀하의 행동에 다음과 같은 서명이 있다고 가정합니다.
public ActionResult MyAction(MyParameter param)
{
if(param.isValid)
return View("valid");
else
return View("invalid");
}
MyParam 클래스 :
public class MyParameter
{
public string UserName{get;set;}
public string Password {get;set;}
public bool isValid
{
//check if password and username is valid.
}
}
그런 다음 커스텀 바인더
public class CustomBinder:IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var p = new MyParam();
// extract necessary data from the bindingcontext like
p.UserName = bindingContext.ValueProvider["username"] != null
? bindingContext.ValueProvider["username"].AttemptedValue
: "";
//initialize other attributes.
}
}