添加web api路由到存在的网站无法修改全局的asax

时间:2014-07-29 16:51:16

标签: asp.net asp.net-mvc asp.net-mvc-4 global-asax

我有一个web api项目,我可以在本地运行它,但是当我将dll发布到网站中的bin文件夹时,没有采用路由配置。由于它有自己的实施,因此无法修改或替换全球的asax。哪里是设置mi web api route config的最佳位置,我怎样才能使用httpmodule?

public class WebApiApplication : System.Web.HttpApplication        
{
      protected void Application_Start()
        {

            AreaRegistration.RegisterAllAreas();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }

更新:

我添加了一个httpmodule,并没有映射路由,正在发送http 404:

public void Init(HttpApplication context) {
            try
            {
                AreaRegistration.RegisterAllAreas();

                var routes = RouteTable.Routes;

                // Controllers with Actions
                // To handle routes like '/api/controller/route'
                routes.MapHttpRoute(
                    name: "ControllerActionAndId",
                    routeTemplate: "api/{controller}/{action}/{id}",
                    defaults: new { id = RouteParameter.Optional },
                    constraints: new { id = @"^\d+$" }
                );

                // Controllers with Actions
                // To handle routes like '/api/controller/route'
                routes.MapHttpRoute(
                    name: "ControllerAndAction",
                    routeTemplate: "api/{controller}/{action}"
                );

                // Controller with ID
                // To handle routes like '/api/controller/1'
                routes.MapHttpRoute(
                    name: "ControllerAndId",
                    routeTemplate: "api/{controller}/{id}",
                    defaults: null,
                    constraints: new { id = @"^\d+$" } // Only integers 
                );

                // Controller Only
                // To handle routes like '/api/controller'
                routes.MapHttpRoute(
                    name: "ControllerOnly",
                    routeTemplate: "api/{controller}"
                );

            }
            catch { }
        } 

1 个答案:

答案 0 :(得分:0)

如果你不能改变全局的asax,你能改变网络配置吗?

使用httpmodule,你会得到像

这样的东西
  <system.webserver>
       <modules>
           <add name="WebApiStartModule" type="myproject.WebApiStartModule, assembly"/>
        </modules>
  <system.webserver>


  public class WebApiStartModule : IHttpModule
  {

       public void Init(HttpApplicationContext) {

             var routes = RouteTable.Routes

             routes.Clear()
             //initialize routing here
       }
  }