我可以使用控制器的路由屬性和屬性有參數,不僅在ASP.NET核心中的常量字符串? ex。我想補充下述定義控制器我可以爲控制器添加參數嗎?
[Route("api/sth/{Id}/sth2/latest/sth3")]
public class MyController : Controller
{
public object Get()
{
return new object();
}
}
我可以使用控制器的路由屬性和屬性有參數,不僅在ASP.NET核心中的常量字符串? ex。我想補充下述定義控制器我可以爲控制器添加參數嗎?
[Route("api/sth/{Id}/sth2/latest/sth3")]
public class MyController : Controller
{
public object Get()
{
return new object();
}
}
可以肯定的,你可以,但是,往往是棘手的,如果你不計劃好。
讓我們假設你的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/
但,如果你結合在同一個控制器的2個行動,它會返回一個500的有2種方法可以迴應你的要求。
您可以在一個類似的方式來使用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)
{
}
}
在ASP.NET Core中,我們也可以使用RoutePrefix? –
我沒有使用.NET Core,所以我不能說,對不起。如果您使用的是.NET Core,我會將其添加到您的問題中。 –