Remove “api” prefix from Web API url

你说的曾经没有我的故事 提交于 2019-12-05 18:08:38

问题


I've got an API controller

public class MyController : ApiController { ... }

By default it is mapped to URL mysite/api/My/Method, and I'd like it to have URL without "api" prefix: mysite/My/Method

Setting controller attribute [RoutePrefix("")] didn't help me.

Are there any other ways to achieve that?


回答1:


The default Registration is usually found in WebApiConfig and tends to look like this

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Attribute routing.
        config.MapHttpAttributeRoutes();

        // Convention-based routing.
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

You need to edit the routeTemplate in the convention-based setup.

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Attribute routing.
        config.MapHttpAttributeRoutes();

        // Convention-based routing.
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Do note that if this project is shared with MVC that the reason for the api prefix was to avoid route conflicts between the two frameworks. If Web API is the only thing being used then there should be no issue.



来源:https://stackoverflow.com/questions/37772816/remove-api-prefix-from-web-api-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!