AJAX Call returning 404(Local) in IIS 7.5 but same works in other IIS

拥有回忆 提交于 2019-12-02 17:14:39

That's normal. You have hardcoded the url to your controller action:

url: '/Controller/FunctionName',

If you deploy your application in a virtual directory in IIS the correct url should be:

url: '/YourAppName/Controller/FunctionName',

That's the reason why you should absolutely never hardcode urls in an ASP.NET MVC application but ALWAYS use url helpers to generate it:

url: '@Url.Action("FunctionName", "Controller")',

and if this AJAX call is in a separate javascript file where you cannot use server side helpers, then you could read this url from some DOM element that you are AJAXifying.

For example let's suppose that you had an anchor:

@Html.ActionLink("click me", "FunctionName", "Controller", null, new { id = "myLink" })

that you AJAXify:

$('#myLink').click(function() {
    $.ajax({
        url: this.href,
        contentType: 'application/json; charset=utf-8',
        type: 'GET',
        .
        .
        .
    )};    
    return false;
});

Notice how we are reading the url from the DOM element which was generated by a helper.

Conclusion and 2 rules of thumb:

  • NEVER EVER hardcode an url in an ASP.NET MVC application
  • ABSOLUTELY ALWAYS use url helpers when dealing with urls in an ASP.NET MVC application
Thanh

Just a complement of Darin's answer that if "the AJAX call is in a separate javascript file where you cannot use server side helpers", use a hidden field to store the url endpoint in the view:

@Html.Hidden("URLEndpointName", Url.Action("FunctionName", "Controller"))

and read that hidden field in your js:

url: $("#URLEndpointName").val(),

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.

You can use double dot in the url:

$.ajax({
   url: '../ControllerName/ActionName',
   .......
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!