路由到 api 工作错误
Route to api work wrong
当我从 http://localhost:5086/ it work great it send to api/FileBrowser, but when i try to make request from http://localhost:5086/Home/Index 向 api 发出 GET 请求时,向 url 添加控制器主页并请求发送到 /Home/api/FileBrowser
请帮助我做错了什么?
具有 2 个方法的 ApiController
public FileBrowserModel Get()
{
var result = new FileBrowserModel();
List<string> drives = new List<string>();
foreach (var drive in DriveInfo.GetDrives())
{
var path = drive.Name;
FileManagerCounter fmCounter = new FileManagerCounter(path);
result.CountTo10Mb += fmCounter.CountTo10Mb;
result.Countfrom10To50Mb += fmCounter.Countfrom10To50Mb;
result.CountFrom100Mb += fmCounter.CountFrom100Mb;
drives.Add(path);
}
result.SubDirectories = new List<string>(drives);
return result;
}
[CacheOutput(ServerTimeSpan = 150)]
[System.Web.Http.HttpGet]
public FileBrowserModel Get(string path)
{
var result = new FileBrowserModel();
try
{
try
{
result.ParentPath = Directory.GetParent(path).FullName;
}
catch (Exception)
{
}
var files = Directory.GetFiles(path).ToList();
result.Files = new List<string>(files);
result.CurrentPath = path;
FileManagerCounter fmCounter = new FileManagerCounter(path);
result.CountTo10Mb = fmCounter.CountTo10Mb;
result.Countfrom10To50Mb = fmCounter.Countfrom10To50Mb;
result.CountFrom100Mb = fmCounter.CountFrom100Mb;
var subDirectories = Directory.GetDirectories(path).ToList();
result.SubDirectories = new List<string>(subDirectories);
}
catch (Exception ex)
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
return result;
}
js 文件
angular.module("FileBrowserApp", [])
.controller("fileBrowserController", function($scope, $http) {
$scope.getFileBrowsing = function (path) {
$scope.isLoading = true;
if (path != null) {
$http({
url: "api/FileBrowser?path=" + encodeURIComponent(path),
method: "GET"
}).success(function (data) {
$scope.fileBrowserModel = data;
$scope.isLoading = false;
});
} else {
$http({
url: "api/FileBrowser",
method: "GET"
}).success(function (data) {
$scope.fileBrowserModel = data;
$scope.isLoading = false;
});
}
};
$scope.getFileBrowsing();
});
路线
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{path}",
defaults: new { path = RouteParameter.Optional }
);
}
}
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 }
);
}
}
编辑:War10ck 的答案是简单的解决方案。
下面是另一种解决方案,可以正确构建相对 url
问题是,您将 url 值硬编码为 "api/FileBrowser"。所以根据当前页面,这个值将是 change.If 你在主页上,它将是 Home/api/FileBrowser
.
你应该做的是建立正确的亲戚url。由于您使用的是 asp.net mvc 页面,您可以利用 Url.Action 辅助方法来构建正确的相对 url。您可以在剃刀视图中生成应用程序路由的值并将其传递给您的 angular controller/data 服务并使用它。
所以在您看来,
<script>
var myApp = myApp || {};
myApp.Urls = myApp.Urls || {};
myApp.Urls.baseUrl = '@Url.Content("~")';
</script>
<script src="~/Scripts/AngularControllerForPage.js"></script>
<script>
var a = angular.module("FileBrowserApp").value("appSettings", myApp);
</script>
并且在您的 angular 控制器中,您可以访问此应用程序设置。
var app = angular.module("FileBrowserApp", []);
var ctrl = function (appSettings) {
var vm = this;
vm.baseUrl = appSettings.Urls.baseUrl;
//build other urls using the base url now
var fileBrowserUrl= vm.baseUrl + "api/FileBrowser";
alert(fileBrowserUrl);
//You can use this variable value for your http call now
$http({
url: fileBrowserUrl+ "?path=" + encodeURIComponent(path),
method: "GET"
}).success(function (data) {
$scope.fileBrowserModel = data;
$scope.isLoading = false;
});
};
app.controller("fileBrowserController", ctrl)
您可以并且应该在您的数据服务和指令等中访问它并使用它来构建正确的url。
您还可以考虑将您的 http 调用从您的 angular 控制器转移到数据服务。
如果您绝对确定您的 Web API 层将始终存在于根域之上一层,那么您可以将 ajax 调用中的网址更改为:
url: "/api/..."
无论站点的结构如何,这都会调用相对于根域的 api。
当我从 http://localhost:5086/ it work great it send to api/FileBrowser, but when i try to make request from http://localhost:5086/Home/Index 向 api 发出 GET 请求时,向 url 添加控制器主页并请求发送到 /Home/api/FileBrowser
请帮助我做错了什么?
具有 2 个方法的 ApiController
public FileBrowserModel Get()
{
var result = new FileBrowserModel();
List<string> drives = new List<string>();
foreach (var drive in DriveInfo.GetDrives())
{
var path = drive.Name;
FileManagerCounter fmCounter = new FileManagerCounter(path);
result.CountTo10Mb += fmCounter.CountTo10Mb;
result.Countfrom10To50Mb += fmCounter.Countfrom10To50Mb;
result.CountFrom100Mb += fmCounter.CountFrom100Mb;
drives.Add(path);
}
result.SubDirectories = new List<string>(drives);
return result;
}
[CacheOutput(ServerTimeSpan = 150)]
[System.Web.Http.HttpGet]
public FileBrowserModel Get(string path)
{
var result = new FileBrowserModel();
try
{
try
{
result.ParentPath = Directory.GetParent(path).FullName;
}
catch (Exception)
{
}
var files = Directory.GetFiles(path).ToList();
result.Files = new List<string>(files);
result.CurrentPath = path;
FileManagerCounter fmCounter = new FileManagerCounter(path);
result.CountTo10Mb = fmCounter.CountTo10Mb;
result.Countfrom10To50Mb = fmCounter.Countfrom10To50Mb;
result.CountFrom100Mb = fmCounter.CountFrom100Mb;
var subDirectories = Directory.GetDirectories(path).ToList();
result.SubDirectories = new List<string>(subDirectories);
}
catch (Exception ex)
{
throw new HttpResponseException(HttpStatusCode.InternalServerError);
}
return result;
}
js 文件
angular.module("FileBrowserApp", [])
.controller("fileBrowserController", function($scope, $http) {
$scope.getFileBrowsing = function (path) {
$scope.isLoading = true;
if (path != null) {
$http({
url: "api/FileBrowser?path=" + encodeURIComponent(path),
method: "GET"
}).success(function (data) {
$scope.fileBrowserModel = data;
$scope.isLoading = false;
});
} else {
$http({
url: "api/FileBrowser",
method: "GET"
}).success(function (data) {
$scope.fileBrowserModel = data;
$scope.isLoading = false;
});
}
};
$scope.getFileBrowsing();
});
路线
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{path}",
defaults: new { path = RouteParameter.Optional }
);
}
}
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 }
);
}
}
编辑:War10ck 的答案是简单的解决方案。
下面是另一种解决方案,可以正确构建相对 url
问题是,您将 url 值硬编码为 "api/FileBrowser"。所以根据当前页面,这个值将是 change.If 你在主页上,它将是 Home/api/FileBrowser
.
你应该做的是建立正确的亲戚url。由于您使用的是 asp.net mvc 页面,您可以利用 Url.Action 辅助方法来构建正确的相对 url。您可以在剃刀视图中生成应用程序路由的值并将其传递给您的 angular controller/data 服务并使用它。
所以在您看来,
<script>
var myApp = myApp || {};
myApp.Urls = myApp.Urls || {};
myApp.Urls.baseUrl = '@Url.Content("~")';
</script>
<script src="~/Scripts/AngularControllerForPage.js"></script>
<script>
var a = angular.module("FileBrowserApp").value("appSettings", myApp);
</script>
并且在您的 angular 控制器中,您可以访问此应用程序设置。
var app = angular.module("FileBrowserApp", []);
var ctrl = function (appSettings) {
var vm = this;
vm.baseUrl = appSettings.Urls.baseUrl;
//build other urls using the base url now
var fileBrowserUrl= vm.baseUrl + "api/FileBrowser";
alert(fileBrowserUrl);
//You can use this variable value for your http call now
$http({
url: fileBrowserUrl+ "?path=" + encodeURIComponent(path),
method: "GET"
}).success(function (data) {
$scope.fileBrowserModel = data;
$scope.isLoading = false;
});
};
app.controller("fileBrowserController", ctrl)
您可以并且应该在您的数据服务和指令等中访问它并使用它来构建正确的url。
您还可以考虑将您的 http 调用从您的 angular 控制器转移到数据服务。
如果您绝对确定您的 Web API 层将始终存在于根域之上一层,那么您可以将 ajax 调用中的网址更改为:
url: "/api/..."
无论站点的结构如何,这都会调用相对于根域的 api。