ASP.NET MVC - ActionFilterAttribute to validate POST data

倖福魔咒の 提交于 2019-12-07 04:24:54

问题


Actually I have an application that is using a WebService to retrieve some clients information. So I was validating the login information inside my ActionResult like:

[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");
    }
}

Where Client.Validate() is a method that returns a boolean based on the information provided on the POST username and password

But I changed my mind and I would like to use that nice ActionFilterAttributes at the beginning of the method so it will just be rendered if the Client.validate() return true, just the same as [Authorize] but with my custom webservice, so I would have something like:

[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')
}

and then inside the ValidateAsClient I would have something like:

public class ValidateAsClient : ActionFilterAttribute
{
    public string username { get; set; }
    public string password { get; set; }

    public Boolean ValidateAsClient()
    {
        return Client.validate(username,password);
    }
}

So my problem is, I don't know exactly how to make it work, because I don't know how to pass the POSTED information to the [ValidateAsClient(username=postedUsername,password=postedPassword)] and also, how could I make the function ValidateAsClient work properly?

I hope this is easy to understand Thanks in advance


回答1:


Something like this probably:

[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
    }
}

And use it like this:

[ValidateAsClient(HttpContext.Request.Form)]



回答2:


You should override the following method.

public override void OnActionExecuting(ActionExecutingContext context)

And from the context object, access your post data.




回答3:


I don't think it's a good idea to use an ActionFilterAttribute in this case. And what you want to do is definitely not the same as Authorize attribute does.

The Authorize attribute just injects a common logic into a controller/action. Which is :

Redirect to login page, if the user is not logged in. Else let the action be executed.

Your ClientLogin action does just what it's supposed to do at the moment.
It would be a bad design to carry that logic over to an ActionFilterAttribute.




回答4:


I would solve this problem with a custom binder in ASP.NET MVC.

Suppose your action will have the following signature.

public ActionResult MyAction(MyParameter param)
{
  if(param.isValid)
    return View("valid");
  else
    return View("invalid");
}

MyParam class:

    public class MyParameter
    {
      public string UserName{get;set;}
      public string Password {get;set;}

      public bool isValid
      {
        //check if password and username is valid.
      }

}

An then the custom binder

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.
        }
}


来源:https://stackoverflow.com/questions/1601333/asp-net-mvc-actionfilterattribute-to-validate-post-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!