【问题标题】:Is it possible to restrict an action method to "only redirect-to access"?是否可以将操作方法​​限制为“仅重定向访问”?
【发布时间】:2021-02-12 14:07:41
【问题描述】:

使用 ASP.NET Core 3.1 - MVC,我有一个 HTTP Post 操作方法,它从客户端获取数据并在数据库上工作。因为这个action方法很长很乱,重复代码很多,所以我决定简化这个action方法,使用Redirect-to。像这样:

[HttpPost]
[ValidateAntiForgeryToken]
[Route("MainActionMethod")]
public async Task<IActionResult> MainActionMethod([FromBody]object jsonData) 
 {
.  .  .  
       if (condition a) 
           return RedirectToAction("Action1");
       if (condition b) 
           return RedirectToAction("Action2");
.  .  . 
}

Action1 必须是 HTTPGet 才能被重定向,因此用户可以输入这样的 URL 并修改我的数据库

http://www.example.com/?param1="Hello"&param2="Stacky"

如何禁用浏览器对HTTP GET Action1 的访问,而只能通过其他操作方法或仅通过重定向访问?

【问题讨论】:

    标签: asp.net-core asp.net-core-3.1


    【解决方案1】:

    Requestheader中有一个属性Referer。如果从浏览器访问,则其值为空。以此来决定后续的处理流程。

    [HttpPost]
    [ValidateAntiForgeryToken]
    [Route("MainActionMethod")]
    public async Task<IActionResult> MainActionMethod([FromBody]object jsonData)
    {
       if (true) 
           return RedirectToAction("Action1");
    }
    public IActionResult Action1()
    {
        StringValues header ;
        Request.Headers.TryGetValue("Referer",out header);
        if (header.Count==0)
        {
            return BadRequest();
        }
        return Ok("Action1");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多