【问题标题】:MVC Web API route not working with parameters. c#MVC Web API 路由不使用参数。 C#
【发布时间】:2018-04-01 09:53:06
【问题描述】:

当我请求没有参数的路由时,我的 web api 工作正常,但是当我添加参数时它没有找到控制器:

这是我的 WebApiConfig.cs:

config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "v1/{controller}/{id}",
            defaults: new { area = "v1", id = RouteParameter.Optional }
        );

这是我在“v1”区域的控制器:

[RoutePrefix("v1/Dummy")]
public class DummyController : ApiController
{
    [HttpGet]
    //[Route("")]
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    [HttpGet]
    [Route("{id:int}")]
    public string Get(int id)
    {
        return "value";
    }

    [HttpPost]
    public void Post([FromBody]string value)
    {
    }

    [HttpPut]
    public void Put(int id, [FromBody]string value)
    {
    }

    [HttpDelete]
    public void Delete(int id)
    {
    }
}

正确的是: 出了什么问题:

有人可以帮忙吗?

编辑:

我在 Application_Start() 中有以下代码:

AreaRegistration.RegisterAllAreas();

System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);

编辑 2:

private void RegisterRoutes()
    {

        RouteTable.Routes.Add(new ServiceRoute("SumiService/Customer", new WebServiceHostFactory(), typeof(SumiyCustomerService)));
        RouteTable.Routes.Add(new ServiceRoute("SumiService", new WebServiceHostFactory(), typeof(SumiService)));

        RouteTable.Routes.Add(new ServiceRoute("goops", new WindsorServiceHostFactory<RestServiceModel>(), typeof(IGoOpsService)));

        RouteTable.Routes.Add(new ServiceRoute("TempService", new WebServiceHostFactory(), typeof(TempService)));
        RouteTable.Routes.Add(new ServiceRoute("Go", new WindsorServiceHostFactory<RestServiceModel>(), typeof(GoBusinessContracts.IGoService)));
    }

【问题讨论】:

  • 你有路由区注册码吗?
  • @duongthaiha 我添加了代码。
  • 您的错误消息来自 MVC,而不是 Web API。你的 MVC 路由配置是什么样的?
  • @Kirk 没有进一步的路由配置。如果你引用的是RouteConfig.cs,它没有在应用程序启动中注册,并且该文件在App_Start中不存在
  • 我是这么理解的。我已尝试使用提供的所有信息重现此内容,但它在我的环境中按预期工作。

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


【解决方案1】:

尝试将 [FromRoute][FromUri] 属性添加到您的 ID 参数:

    [HttpGet]
    [Route("{id:int}")]
    public string Get([FromRoute] int id)
    {
        return "value";
    }

【讨论】:

  • 两个属性都不会改变行为?你试过 [FromUri] 吗?
  • 不,他们没有。是的,我都试过了。鉴于请求甚至没有到达路由..我几乎不认为这些属性会改变这件事。
  • 好的,你搭建新区v1了吗?您的解决方案中有一些 v1AreaRegistration.cs 吗?默认情况下,脚手架区域添加特定区域路由的此类注册。删除此文件/路由注册
猜你喜欢
  • 2013-05-14
  • 1970-01-01
  • 2019-11-21
  • 2013-06-23
  • 1970-01-01
  • 1970-01-01
  • 2016-12-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多