我刚刚在我的ASP.NET MVC4项目中添加了一个新的ApiController(我已经在Controllers文件夹中有一个ApiController),名为ServerInfoController。我使用CRUD模板选项创建了这个;这是它的样子:
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebFrontend.Models;
namespace WebFrontend.Controllers
{
public class ServerInfoController : ApiController
{
// GET api/serverinfo
public Dictionary<string, string> Get()
{
var settings = GlobalStaticVars.StaticCore.LoadServerSettings("Last", "Server");
if (settings != null)
{
return new Dictionary<string, string>
{
{"ServerIP", settings.Address},
{"ServerPort", settings.Port.ToString()}
};
}
return new Dictionary<string, string>
{
{"ServerIP", ""},
{"ServerPort", ""}
};
}
}
}
但是,每次尝试在浏览器中导航到该资源时,都会收到404错误。我知道我的路由已正确注册,因为我的其他控制器仍可在/ api端点访问。
以下是在WebApiConfig.cs中配置的路由(它是默认路由):
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
答案 0 :(得分:1)
您不需要{action}参与路线。这是默认路由:
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}