将Web Api MapHttpRoute映射到Base Url

时间:2017-08-28 09:09:26

标签: c# asp.net-mvc asp.net-mvc-4 asp.net-web-api asp.net-mvc-routing

嗨,我有一个控制器,如下所示,

[RoutePrefix("")]
public class ApiInformationController : Controller
{
    public ActionResult Index()
    {
        var info = new ApplicationInformation
        {
            ApplicationName = "Test App",
            DatabaseName = "SQL Server 2012",
            ApplicationVersion = "3.10.0"
        };
        return Json(info, JsonRequestBehavior.AllowGet);
    }
}

我还在WebApiConfig中配置了路由,因为我不想单独使用RouteConfig,

private static void ConfigureRoutes(HttpConfiguration config)
    {
        _config = config;

        // Web API routes
        _config.MapHttpAttributeRoutes();

        _config.Routes.MapHttpRoute("Default", "{controller}/{action}/{id}",
            new {controller = "ApiInformation", action = "Index", id = RouteParameter.Optional});
        _config.Routes.MapHttpRoute(name: "DefaultApi", routeTemplate: "api/{controller}/{id}",
            defaults: new {id = RouteParameter.Optional});
    }

当我尝试访问基本网址时,我希望显示ApiInformation。 例如,当我尝试 http://localhost:23175/ 时,我希望Api能够调用ApiInformationController的索引。我在这里做错了什么?

当我调用网址时,我收到以下回复, enter image description here

1 个答案:

答案 0 :(得分:2)

需要修改MapHttpRoute的routeTemplate。

WebApiConfig喜欢,

config.Routes.MapHttpRoute("Default", "{controller}/{action}/{id}",
        new { controller = "ApiInformation", action = "Index", id = RouteParameter.Optional });

你收到的方式,

[System.Web.Http.HttpGet]
public IHttpActionResult Index()
{
    var info = new ApplicationInformation
    {
        ApplicationName = "Test App",
        DatabaseName = "SQL Server 2012",
        ApplicationVersion = "3.10.0"
    };
    return Json(info);
}

希望它能帮到你