h bob
h bob

Reputation: 3780

Prevent user from accessing an action which is accessible by code

I use the latest MVC, with attribute routing.

When a user submits a contact form, it then redirects to a "thank you for submitting your info" view, with route foo.com/success.

How can I configure it so that my code can redirect to that success action as usual, but the user cannot navigate to it directly?

Upvotes: 0

Views: 67

Answers (2)

M.Azad
M.Azad

Reputation: 3763

If you want prevent user to access action with url your action mustn't has [HttpGet] Or you must set AuthorizeAttribute on your action.for this use ajax request to call your action and send your success message to client with Json

    //Client Side
$.ajax({
    type: "POST",
    url: 'Action URL',
    contentType: "application/json; charset=utf-8",
    data: {id :1},
    dataType: "json",
    success: function(result) {
    alert(result.message);        
    }
    });


[HttpPost]
public ActionResult MyAction(string id){
   return Json(new {message="Your Message"});
}

Upvotes: 1

asdf_enel_hak
asdf_enel_hak

Reputation: 7640

if you do not have a link in page, user won't access it directly.
Otherwise if user cannot access it, you cannot access it via code neither.

[HttpGet]
public ActionResult MyAction(){
   //...
   return RedirectToAction("Success");
}

[HttpGet]
public ActionResult Success(){
   ViewBag.Result = "thank you for submitting your info";
   return View();
}

Upvotes: 1

Related Questions