【问题标题】:Can we use Bind attribute with Get action method while passing parameter in MVC?在 MVC 中传递参数时,我们可以使用 Bind 属性和 Get 操作方法吗?
【发布时间】:2019-01-14 21:08:54
【问题描述】:

我在使用 HPFortify 时遇到了另外 2 个错误以及以下给定代码的主要问题:
1. ASP.NET MVC 不良做法:没有防伪造验证的控制器操作 [注意:由于 Bind 属性,它可能会询问此错误。因此,我将 ValidateAntiForgeryToken 放入代码中。但是,它再次要求将动词更改为 POST]
2. ASP.NET MVC 不良做法:控制器操作不限于 POST
它是正确的还是需要改变什么?

[AcceptVerbs(HttpVerbs.Get)]   
[ValidateAntiForgeryToken]    
public Actionresult Index([Bind(Include="Eid, Eage")]EmpModel objEmpModel)    
{   
return view(objEmpModel);    
} 

【问题讨论】:

    标签: asp.net-mvc fortify


    【解决方案1】:

    您可以简单地使用[HttpPost] 来处理这样的复杂对象:

    [HttpPost]   
    [ValidateAntiForgeryToken]    
    public Actionresult Index(EmpModel objEmpModel)    
    {   
    return view(objEmpModel);    
    }
    

    或者如果你想让你的代码工作,使用这个:

    [HttpGet]   
    [ValidateAntiForgeryToken]    
    public Actionresult Index([FromUri]EmpModel objEmpModel)    
    {   
    return view(objEmpModel);    
    }  
    

    注意: 对于类等复杂类型,web-api 会尝试从 body 中读取数据,因为您使用的是 [HttpGet] 方法,因此 [FromUri] 属性会覆盖默认约定并读取来自 Uri 而不是正文的数据。更多信息 - https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

    【讨论】:

    • Bind 包括大约 20-25 个参数。 HPFortify 通过明确定义为 GET 的方法声明它需要 antiforgerytoken。使用 ValidateAntiForgeryToken 的方法应该是 POST。所以,没有弄错那里?
    • [AcceptVerbs(HttpVerbs.Get)] 如果你把它改成[AcceptVerbs(HttpVerbs.Post)] ,会发生什么?
    • 什么也没发生。因为,它通过 Bind 将参数带入模型并返回视图,无需任何数据库或服务调用。令人惊讶的是,当我编写 ValidateAntiForgeryToken 时,第一个错误得到了解决。好吗?如果将其更改为 POST?还是将第二个错误视为误报?
    猜你喜欢
    • 2015-10-26
    • 2020-03-04
    • 1970-01-01
    • 2015-12-29
    • 2020-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多