Solved

MVC Routing for AJAX call not working when on server?

Posted on 2015-02-05
23
624 Views
Last Modified: 2015-02-06
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
Comment
Question by:flynny
  • 13
  • 6
  • 4
23 Comments
 

Author Comment

by:flynny
ID: 40591281
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
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 40591282
Have you run Fiddler (or equivalent) along side to see what is actually being sent to the server?
0
 
LVL 7

Expert Comment

by:James Bilous
ID: 40591283
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
 

Author Comment

by:flynny
ID: 40591284
and my post method in my home controller is

 [HttpPost]
        public Boolean SendForm(InstantQuote form) {

Open in new window

0
 

Author Comment

by:flynny
ID: 40591296
@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
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 40591304
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
 

Author Comment

by:flynny
ID: 40591311
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
 

Author Comment

by:flynny
ID: 40591315
@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
 
LVL 74

Expert Comment

by:käµfm³d 👽
ID: 40591320
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
 

Author Comment

by:flynny
ID: 40591325
Hi Kaufmed,

sorry could you explain further? I'm not fully understand what your saying here?
0
 
LVL 7

Expert Comment

by:James Bilous
ID: 40591334
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
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:flynny
ID: 40591336
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
 

Author Comment

by:flynny
ID: 40591341
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
 
LVL 7

Expert Comment

by:James Bilous
ID: 40591365
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
 
LVL 74

Assisted Solution

by:käµfm³d 👽
käµfm³d   👽 earned 250 total points
ID: 40591370
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
 

Author Comment

by:flynny
ID: 40591403
@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
 
LVL 7

Expert Comment

by:James Bilous
ID: 40591441
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
 

Author Comment

by:flynny
ID: 40591451
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
 
LVL 7

Expert Comment

by:James Bilous
ID: 40591455
No problem. What type of response are you expecting, JSON? XML?
0
 

Author Comment

by:flynny
ID: 40591460
its a basically posting a some info to the server which then sends an email returning a boolean.
0
 
LVL 7

Accepted Solution

by:
James Bilous earned 250 total points
ID: 40591497
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
 

Author Comment

by:flynny
ID: 40593160
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
 

Author Closing Comment

by:flynny
ID: 40593162
Amazing support and fast, reliable and helpful comments.
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Suggested Solutions

Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

17 Experts available now in Live!

Get 1:1 Help Now