• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3041
  • Last Modified:

MVC Routing for AJAX call not working when on server?

HI all,

I have a successful AJAX Call to a controller method /Home/SendForm which is working perfectly locally on my machine.

However when I load it to our server I am getting a 404 error returning the the $.ajax() error method?

Now all files have successfully been uploaded (including routing) to the server. Has anyone seen this error before?

The server is running IIS 7.5.
0
flynny
Asked:
flynny
  • 13
  • 6
  • 4
2 Solutions
 
flynnyAuthor Commented:
Just to add my ajax call is as follows;

 $.ajax({
                    url: '@Url.Action("SendForm", "Home")', 
                    contentType: "application/json",
                    type: "POST",
                    datatype: "json",
                    data: JSON.stringify(form),
                    error: function (xmlHttpRequest, errorText, thrownError) {
                        alert(xmlHttpRequest + "|" + errorText + "|" + thrownError);
                        alert(xmlHttpRequest.responseText);
                        alert(xmlHttpRequest.statusText);
                    },
                    success: function (data) {
                        //alert(data);
                        if (data) {
                            $('#submitting').slideUp("slow");
                            $('#complete').slideDown("slow");
                        }
                    }
                });

Open in new window

0
 
käµfm³d 👽Commented:
Have you run Fiddler (or equivalent) along side to see what is actually being sent to the server?
0
 
James BilousSoftware EngineerCommented:
When you make an AJAX request to "/Some/Path" from a file, lets say, "http://your.domain.com/folder2/file1", the url requested will be fully formed as "http://your.domain.com/Some/Path" or in your case "http://your.domain.com/Home/SendForm". Are you sure your routes are set up to handle the request at this URL?
0
Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
flynnyAuthor Commented:
and my post method in my home controller is

 [HttpPost]
        public Boolean SendForm(InstantQuote form) {

Open in new window

0
 
flynnyAuthor Commented:
@Kaufmed - no I havent used fiddler I will download and test now.

@james - I have checked the routing and should be all ok? The is no cross domain with the call and I have tried hardocding the url, i.e. http://mydomain.com/Home/SendForm.
0
 
käµfm³d 👽Commented:
For giggles, if you hard-code the path without a leading slash, does it work?

e.g.

$.ajax({
                    url: 'Home/SendForm',
...

Open in new window

0
 
flynnyAuthor Commented:
Ok I have installed and run fiddler and heres the RAW data

POST http://dev.mydomain.co.uk/Home/SendForm HTTP/1.1
Host: dev.mydomain.co.uk
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0
Accept: */*
Accept-Language: en-GB,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/json; charset=UTF-8
X-Requested-With: XMLHttpRequest
Referer: http://dev.mydomain.co.uk/
Content-Length: 200
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

{"amount":"255000","duration":"12","security":"1025000","loan":"500000","securityType":"Residential","charge":"1st Charge","fullName":"matt","email":"matt@test.co.uk","phone":"1234567"}
0
 
flynnyAuthor Commented:
@Kaufmed,

I hardcoded but it resolved the url to /Home/SendForm.

Is there anything I can check in the routing?

I did find this article

http://stackoverflow.com/questions/9703090/http-404-page-not-found-in-web-api-hosted-in-iis-7-5

but this change has made no difference (its still working locally with this change to the wb.config, just not on the server)
0
 
käµfm³d 👽Commented:
When you have that leading slash in there, which is what Url.Action is doing, it tells the server to look in its root, not the application's root. You can see this in your POST above. You need to either nix the leading slash, or you need to append the application name to the front of the url value.
0
 
flynnyAuthor Commented:
Hi Kaufmed,

sorry could you explain further? I'm not fully understand what your saying here?
0
 
James BilousSoftware EngineerCommented:
Does your application live in the root directory of your web server?

Can you post the relevant bit of code you are using to handle the request "/Home/Sendform" in your routes?
0
 
flynnyAuthor Commented:
Hi,

Sorry yes the application is in the root, i.e. dev.mydomain.co.uk is where the site resides.

for rerefence here the routeconfig

public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }

Open in new window

0
 
flynnyAuthor Commented:
also (I hope it helps) heres the raw fiddler output from the localhost which is successful;

POST http://localhost:13071/Home/SendForm HTTP/1.1
Host: localhost:13071
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0
Accept: */*
Accept-Language: en-GB,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/json; charset=UTF-8
X-Requested-With: XMLHttpRequest
Referer: http://localhost:13071/
Content-Length: 193
Cookie: _ga=GA1.1.551316189.1422270859
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

{"amount":"255000","duration":"12","security":"1025000","loan":"500000","securityType":"Residential","charge":"1st Charge","fullName":"matt","email":"matt@test.co.uk","phone":"1234567"}

Open in new window

0
 
James BilousSoftware EngineerCommented:
I found the following with a bit of searching which may be relevant:

What I'd found on my setup of IIS7.5 is that the 'Handler Mapping' has a resource named 'OPTIONSVerbHandler' is not set in the right order hence return back as Unknown.

This work for me where my localhost ajax was calling my network server, which has a different name, that it shouldn't give me a CORS issue, but it did and this was my solution.

Open IIS and click on your server name on the left pane. On the right pane double-click 'Handler Mappings' in the middle pane. On the right pane, select 'View Ordered List'. From there find 'OPTIONSVerbHandler' and 'svc-ISAPI-4.0_32bit', move 'OPTIONSVerbHandler' up until it is above 'svc-ISAPI-4.0_32bit'.

Make sure your 'handler' inside your ajax call does not have 'Access-Control-Allow-Origin' in it.
0
 
käµfm³d 👽Commented:
Say I have an application named "SuperFantastic" deployed to my web server at www.example.com. So to get to my welcome page I might have a user go to:


(Mind you in a real-world scenario we wouldn't have the user typing out "Home" and "Index". This is just for example.) So you can plainly see my application name in the URL. Now, if I were to try and call methods belonging to my application, the server has to know how to route the calls I make to my application. If I put a leading slash into my request:

$.ajax({
                    url: '/Home/SendForm',
...

Open in new window


...then the web server will think that I want to look at its root. In other words, it will think that the URL I was trying to hit was:


So where is my SuperFantastic app? If I instead remove the slash:

$.ajax({
                    url: 'Home/SendForm',
...

Open in new window


...then the webserver hunts relative to the page that made the request. And actually, I'm a bit incorrect in the sample above. "Home" should not be in there. It should instead be:

$.ajax({
                    url: 'SendForm',
...

Open in new window


...because both "Index" and "SendForm" are both under "Home" as far as the webserver knows. So in actuality, my previous hard-coding suggestion should be:

$.ajax({
                    url: 'SendForm',
...

Open in new window


Mind you that this only applies to "Index" or any other view that falls under "Home". If you trying to go to a different controller, then you'd need to adjust accordingly.
0
 
flynnyAuthor Commented:
@Kaufmed,

Thanks for the explaination. The site is under the root directory of the dev.mydomain.co.uk.

so navigating to dev.mydomain.co.uk/Home/Index returns the home view. dev.mydomain.co.uk/Home/Contact is returnign the contact page etc.

I tried simply hardocding both 'SendForm' and 'Home/SendForm' again but this still gives the 404 error (and same results in fiddler).

@James,

thanks for the link I have moved the handler above the said svc-ISAPI etc but this is still giving the 404 error message.
0
 
James BilousSoftware EngineerCommented:
Strange indeed.

Can you view the post in Firebug or Developer tools and post the response headers you're getting? I have a feeling its an IIS configuration issue.
0
 
flynnyAuthor Commented:
James,

No problem and thanks again guys for taking the time to help me with this.

the raw request from firefox is

Host: dev.mydomain.co.uk
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0
Accept: */*
Accept-Language: en-GB,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/json; charset=UTF-8
X-Requested-With: XMLHttpRequest
Referer: http://dev.mydomain.co.uk/
Content-Length: 189
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

Open in new window


and the raw response is

Cache-Control: private
Content-Length: 1916
Content-Type: text/html; charset=utf-8
Date: Tue, 03 Feb 2015 16:35:49 GMT
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET

Open in new window


does that shed any light on the issue?
0
 
James BilousSoftware EngineerCommented:
No problem. What type of response are you expecting, JSON? XML?
0
 
flynnyAuthor Commented:
its a basically posting a some info to the server which then sends an email returning a boolean.
0
 
James BilousSoftware EngineerCommented:
It looks like with asp.NET there is a virtual directory name at play when the application is deployed, so the correct route for "/Home/SendForm/" becomes "/MyApplication/Home/SendForm". So no matter what, you can't hardcode the URL, you must use '@Url.Action("FunctionName", "Controller")'. Curiously, I see you were using this originally - definitely switch back to using that helper and check the post to make sure its going to "/YourApplicationName/Home/Sendform" when deployed.
0
 
flynnyAuthor Commented:
James and Kaufmed,

sorry for the delay in coming back you. After tinkering I finally managed to get it working. Although I'm not entirely sure what was going on.

First of all I tried reuploading the entire site, which made no difference, so I then deleted the site from IIS, recreated it and reuploaded the site again and it magically started working?

From googling I'm not sure whether creating a new app pool maybe sorted this, but it workig anyway and I thought I'd share how it was fixed.

I'll split the points between you and once again, many thanks for your time and input.
0
 
flynnyAuthor Commented:
Amazing support and fast, reliable and helpful comments.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

  • 13
  • 6
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now