Is there a way of detecting if a Controller is getting posted to directly, or the action is a result of a previous form being posted?
A:
Not sure if I understand your question, but if you are asking about the difference between a user typying in an address into their browser's address bar and pressing enter (accessing your page via the GET verb) vs. being already on a page and hitting a form submit button (usually a POST verb, though it can sometimes also be a GET) then you can look at the value of the HttpRequest.HttpMethod property:
public ActionResult MyMethod() {
if(this.Request.HttpMethod == "POST") {
// form submitted
}
if(this.Request.HttpMethod == "GET") {
// accessed directly
}
}
If you want to restrict your action method to only handle a particular http verb you can also use attributes:
[HttpGet]
public ActionResult MyMethod() {
// only invoked if the request is a GET
}
[HttpPost]
public ActionResult MyMethod(string formInput) {
// only invoked if the request is a POST
}
marcind
2010-09-08 17:39:23
I was thinking if the request was posted from a browser or was begin executed from something other than a browser. I assume the user-agent would be one place to check, but that can be spoofed I believe.
SyntaxC4
2010-09-08 18:45:19
@SyntaxC4 yes, any header information can be spoofed by the client. Perhaps you should clarify why you need to know this?
marcind
2010-09-08 20:46:14