Pavel Jounda
Pavel Jounda

Reputation: 219

Sitecore AJAX POST: Could not invoke action method

We have developed a site with multiple controllers that accept GET and POST and return views and JSON, and everything works fine in our Development environment.

But on the client's acceptance server we have an issue: all the GETs return well their results, but the POSTs return an error described here by John West. The Stacktrace is identical.

System.InvalidOperationException: Could not invoke action method: askquestion. Controller name: Assistance. Controller type: [Namespace].Assistance.Controllers.AssistanceController

We use the approach of defining the route for each controller:

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <pipelines>
      <initialize>
        <processor type="[Namespace].Assistance.Pipelines.RegisterWebApiRoutes, [Namespace].Assistance"
                   patch:before="processor[@type='Sitecore.Mvc.Pipelines.Loader.InitializeRoutes, Sitecore.Mvc']" />
      </initialize>
    </pipelines>
  </sitecore>
</configuration>

The processor is like this:

public class RegisterWebApiRoutes
{
    public void Process(PipelineArgs args)
    {
        RouteTable.Routes.MapRoute(
            name: "Assistance.Api",
            url: "api/assistance/{action}",
            defaults:new {controller = "Assistance" });
    }
}

The action method is like this

[HttpPost]
public ActionResult AskQuestion(AskQuestionViewModel model)
{
    if (ModelState.IsValid)
    {
        ....

        return View("Confirmation");
    }
    else
    {
        return View(model);
    }
}

What is happening? Somehow Sitecore blocks AJAX POST requests. Definitely, this is the configuration issue. Where should I look?

Upvotes: 4

Views: 2742

Answers (1)

Pavel Jounda
Pavel Jounda

Reputation: 219

OK, I have found the source of the issue.

They had URL Rewrite Module with one rule: LowerCaseRule1 (or it may be any other). But when it made it's work, the request turned to GET. Then the controller could not find the corresponding GET action and voila: could not invoke the action method.

I simply added the exception in rewrite rules and it worked.

<rewrite>
  <rules>
    <rule name="LowerCaseRule1" stopProcessing="true">
      <match url="[A-Z]" ignoreCase="false" />
      <action type="Redirect" redirectType="Permanent" url="{ToLower:{URL}}" />
      <conditions>
        <add input="{URL}" pattern="^.*\.(axd|ashx|asmx|lic|ico|swf|less|aspx|ascx|css|js|jpg|jpeg|png|gif)$" negate="true" ignoreCase="true" />                

        <!-- here is my exception -->
        <add input="{URL}" pattern="/api/assistance" negate="true" />   
      </conditions>
    </rule>
  </rules>
</rewrite>

Upvotes: 2

Related Questions