直接访问操作时找不到命名路由,但通过AJAX访问时找到
本文关键字:访问 AJAX 操作 找不到 路由 | 更新日期: 2023-09-27 18:20:03
我有一个命名的路由:
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
当直接访问操作时,此行返回空:
VirtualPathData vpd = RouteTable.Routes.GetVirtualPath(null, "OfficeByZipCode", route);
但是,当通过AJAX调用相同的操作时,它工作得很好。
两者之间的明显区别是,一个是我通过POST(AJAX)访问,另一个是通过GET(URL)访问。如果我将AJAX操作更改为GET,我会收到同样的错误。为什么这会有所不同?
更改GET Url以使zipCode成为参数(例如http://localhost/RLOService/test/RetrieveByZipCode?zipCode=92677
)