2016-10-06 27 views
0

我可以使用控制器的路由属性和属性有参数,不仅在ASP.NET核心中的常量字符串? ex。我想补充下述定义控制器我可以为控制器添加参数吗?

[Route("api/sth/{Id}/sth2/latest/sth3")] 
public class MyController : Controller 
{ 
    public object Get() 
    { 
     return new object(); 
    } 
} 

回答

1

可以肯定的,你可以,但是,往往是棘手的,如果你不计划好。

让我们假设你的owin Startup类设置为默认与app.UseMvc()

下面这段代码工作正常,返回["value1", "value2"]独立价值的WebAPI路线{id}

curl http://localhost:5000/api/values/135/foo/bar/

[Route("api/values/{id}/foo/bar")] 
public partial class ValuesController : Controller 
{ 
    [HttpGet] 
    public IEnumerable<string> Get() 
    { 
     return new string[] { "value1", "value2" }; 
    } 
} 

这个作品也很好,在这种情况下返回路由参数中的指定值135

curl http://localhost:5000/api/values/135/foo/bar/

​​3210

,如果你结合在同一个控制器的2个行动,它会返回一个500的有2种方法可以回应你的要求。

1

您可以在一个类似的方式来使用RoutePrefix,然后根据需要添加Route s到每个方法。在路由前缀中定义的参数仍然以与在方法的路由中指定相同的方式传递给方法。

例如,你可以这样做:

[RoutePrefix("api/sth/{id}/sth2/latest/sth3")] 
public class MyController : ApiController 
{ 
    /// <example>http://www.example.com/api/sth/12345/sth2/latest/sth3</example> 
    [Route()] // default route, int id is populated by the {id} argument 
    public object Get(int id) 
    { 
    } 

    /// <example>http://www.example.com/api/sth/12345/sth2/latest/sth3/summary</example> 
    [HttpGet()] 
    [Route("summary")] 
    public object GetSummary(int id) 
    { 
    } 

    /// <example>http://www.example.com/api/sth/12345/sth2/latest/sth3/98765</example> 
    [HttpGet()] 
    [Route("{linkWith}")] 
    public object LinkWith(int id, int linkWith) 
    { 
    } 
} 
+0

在ASP.NET Core中,我们也可以使用RoutePrefix? –

+0

我没有使用.NET Core,所以我不能说,对不起。如果您使用的是.NET Core,我会将其添加到您的问题中。 –

相关问题