简体   繁体   English

将Web Api MapHttpRoute映射到基本网址

[英]Map Web Api MapHttpRoute to Base Url

Hi I have a Controller as shown below, 嗨,我有一个控制器,如下所示,

[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);
    }
}

I also configured the routes in WebApiConfig as I do not want to use RouteConfig separately, 我还配置了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});
    }

When I try and access the base url, I want the ApiInformation to be displayed. 当我尝试访问基本URL时,我希望显示ApiInformation。 For Example when I try http://localhost:23175/ I would like the Api to call the Index of ApiInformationController. 例如,当我尝试http:// localhost:23175 /时,我希望Api调用ApiInformationController的索引。 What am I doing wrong here? 我在这里做错了什么?

Current when I call the url I am getting the following response, 当前,当我调用url时,我得到以下响应, 在此处输入图片说明

Need to modify MapHttpRoute's routeTemplate. 需要修改MapHttpRoute的routeTemplate。

WebApiConfig like, WebApiConfig之类的,

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

And how you receive, 以及您如何获得

[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);
}

Hope it will help you 希望对您有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM