ehsan_kabiri_33
ehsan_kabiri_33

Reputation: 386

Is it possible to restrict an action method to "only redirect-to access"?

Using ASP.NET Core 3.1 - MVC, I have an HTTP Post action method that gets data from a client and works on database. Because this action method was very long and untidy and many repeated codes, I decided to simplify this action method and use Redirect-to. Something like this :

[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 must be HTTPGet to be redirected and so a user can type a URL like this and modify my database

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

How could I disable access to HTTP GET Action1 from the browser and be accessed only from other action methods or only by redirect-to?

Upvotes: 0

Views: 348

Answers (1)

Karney.
Karney.

Reputation: 5031

There is an attribute Referer in the header of Request. If it is accessed from a browser, its value is empty. Use this to determine the subsequent processing procedure.

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

Upvotes: 1

Related Questions