指定的WebAPI使用AttributeRouting默认的控制器/动作路线 [英] Specify default controller/action route in WebAPI using AttributeRouting

查看:685
本文介绍了指定的WebAPI使用AttributeRouting默认的控制器/动作路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个人如何使用一套的AttributeRouting而不是的WebAPI使用默认RouteConfiguration时默认的控制器使用。
即摆脱了评论code节,因为这使用AttribteRouting时是多余的。

 公共类RouteConfig
    {
       公共静态无效的RegisterRoutes(RouteCollection路线)
       {
        routes.IgnoreRoute({}资源个.axd / {*} PATHINFO);
        //routes.MapRoute(
        //名称:默认,
        // URL:{控制器} / {行动} / {ID}
        //默认:新{控制器=家,行动=索引,ID = UrlParameter.Optional}
        //);       }
     }

如果我评论上面的部分,并尝试运行的WebAPI应用程序,我得到以下错误,因为没有定义默认主页的控制器/动作。
HTTP错误403.14 - 禁止
Web服务器配置为不列出此目录的内容。

我如何指定通过属性的路径路由的Home控制器/动作?

编辑:code样品:<​​/ P>

 公共类HomeController的:控制器
{
    [得到()]
    公众的ActionResult指数()
    {
        返回查看();
    }    公众的ActionResult帮助()
    {
        VAR探险= GlobalConfiguration.Configuration.Services.GetApiExplorer();
        返回查看(新ApiModel(资源管理器));
    }
}


解决方案

你试过以下内容:

  // [路线preFIX()]
公共类HomeController的:控制器
{
    [得到()]
    公众的ActionResult指数()
    {
        返回查看();
    }
}

这将网址模板集合中添加路由,并为控制器和动作默认为家和分别索引。

How does one set the default controller to use when using AttributeRouting instead of the default RouteConfiguration that WebAPI uses. i.e. get rid of the commented code section since this is redundant when using AttribteRouting

    public class RouteConfig
    {
       public static void RegisterRoutes(RouteCollection routes)
       {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        //routes.MapRoute(
        //    name: "Default",
        //    url: "{controller}/{action}/{id}",
        //    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        //);

       }
     }

If I comment the section above and try to run the webapi app, I get the following error since there is no default Home controller/action defined. HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents of this directory.

How can I specify the route via Attribute routing for the Home controller/action?

EDIT: Code Sample:

 public class HomeController : Controller
{
    [GET("")]
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Help()
    {
        var explorer = GlobalConfiguration.Configuration.Services.GetApiExplorer();
        return View(new ApiModel(explorer));
    }
}

解决方案

Have you tried the following:

//[RoutePrefix("")]
public class HomeController : Controller
{
    [GET("")]
    public ActionResult Index()
    {
        return View();
    }
}

This will add a route in the collection with url template as "" and defaults for controller and action to be "Home" and "Index" respectively.

这篇关于指定的WebAPI使用AttributeRouting默认的控制器/动作路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆