直接访问操作时找不到命名路由,但在通过AJAX访问时找到

时间:2014-08-28 17:01:24

标签: c# asp.net-mvc-5

我有一条命名路线:

routes.MapRoute(
    name: "OfficeByZipCode",
    url: "RetrieveOffice/ZipCode/{zipcode}",
    defaults: new { controller = "RLO", action = "RetrieveOfficeByZipCode" }
    );

我正在检索操作中的命名路径:

public ActionResult RetrieveByZipCode(string zipCode)
{
    try
    {
        Office obj = null;
        string urlOffice;
        //build a route dictionary that includes the zip code
        RouteValueDictionary route = new RouteValueDictionary
        {
            {"zipcode", zipCode}
        };
        //build the relative path for the route to retrieve JSON data
        VirtualPathData vpd = RouteTable.Routes.GetVirtualPath(null, "OfficeByZipCode", route);
        //combine the relative path with the site's root path
        //use the config value rather than HttpContext.Current.Request.Url to overcome issues that arise from Load Balancers and SSL offloading 
        urlOffice = String.Concat(Properties.Settings.Default.RootUrl, vpd.VirtualPath);
        //the rest of the code. not important for this example

现在,我通过以下两种方式之一访问此操作:

一个,通过AJAX,从另一个页面:

$.ajax({
    url: "Test/RetrieveByZipCode",
    type: "POST",
    data: JSON.stringify(formData),
    dataType: "html",
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        $("#content").html(data);
    },
    error: function (error) {
        alert("Error");
    }
});

二,直接通过浏览器:

http://localhost/RLOService/test/RetrieveByZipCode/92677

直接访问操作时,此行返回null:

VirtualPathData vpd = RouteTable.Routes.GetVirtualPath(null, "OfficeByZipCode", route);

但是,当通过AJAX调用相同的动作时它可以正常工作。

两者之间的明显区别是我通过POST(AJAX)访问的另一个,我通过GET(URL)访问的另一个。如果我将AJAX操作更改为GET,则会收到相同的错误。为什么会有所作为?

1 个答案:

答案 0 :(得分:2)

更改您的GET Url以使zipCode成为参数(例如http://localhost/RLOService/test/RetrieveByZipCode?zipCode=92677

相关问题