1
訪問時命名的路由直接訪問操作時沒有發現,卻發現我有一個名爲路線:通過AJAX
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,則會收到相同的錯誤。爲什麼這會有所作爲?
它期待一個網址爲http://host..../RetrieveOffice/ZipCode/ {}郵政編碼和你的直接URL犯規匹配用它 – HaBo 2014-08-28 20:07:16
@HaBo:我不確定你的意思。這怎麼解釋POST和GET之間的行爲差異? – 2014-08-28 22:47:40