Use of Http Accept Verbs in MVC

Hi Friends,

Let me give one scenario, where in it becomes very necessary to use HTTP Accept verbs to identify the action whether it’s a Get Request or Post or Delete or Put or combination of any these.

Let’s look @ the below example

public ActionResult Search(string name=”Titanic”)
{
var message = Server.HtmlEncode(name);
return Content(message);
}

public ActionResult Search()
{

return Content(“Hello world”);
}

when you build the solution, it will build successfully, but when you invoke the app, it will give you below error as shown below.

MVC_accept_verb

Here, what happened exactly, MVC framework tries to invoke the search action but unable to distinguish between the same, hence produced the exception. so, for these kind of scenarios, we have HTTP Accept verbs which literally tells the C# compiler to treat one response for HTTP Get request and the other one for HTTP Post.

[HttpGet]
public ActionResult Search(string name=”Titanic”)
{
var message = Server.HtmlEncode(name);
return Content(message);
}

[HttpPost]
public ActionResult Search()
{

return Content(“Hello world”);
}

Now, when i do the build and refresh the browser, it will produce the desired result. Actual scenario, will be explained in a much cleaner way in the upcoming workshop for ASP.Net MVC. Till then stay tuned and happy coding.

Thanks,
Rahul

2,283 total views, 1 views today