如何在 asp.net-core-webapi 中创建路由?
How to create a routing in asp.net-core-webapi?
我正在尝试在我的 .net 核心网站中实施基本路由 api。
我有一个这样的控制器:
[Route("api/[controller]")]
public class FooController : Controller
{
//out of the box
[HttpGet("[action]")] //get the list
public IEnumerable<Foo> Get()
{
//omitted
}
//added: request detail request///
[HttpGet("[action]/{fooid}")]
public Foo Get(string fooid)
{
//omitted
}
}
我正在尝试使以下路线有效:
详细信息:
http://localhost:2724/api/Product/Get?fooid=myfoo1
还有一个通用的列表:
http://localhost:2724/api/Product/Get
问题是 ?fooid=
的调用以 IEnumerable
版本结束,我似乎无法正确处理。
我尝试了各种句法变体来克服这个问题,例如:[HttpGet("{fooid}")]
但这似乎没有帮助。
我知道我可以重命名该方法,但我这样做是为了练习。
我也知道索取文件还没有完成,但欢迎就此事提供任何帮助。
我也试过添加路由:
app.UseMvc(routes =>
{
routes.MapRoute( //default
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "fooid",
template: "{controller=Home}/{action=Index}/{fooid?}");
routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new { controller = "Home", action = "Index" });
});
我尝试了here中描述的一些方法,但没有成功。
你能告诉我一些方向吗?
您的 URL 参数版本不正确。它需要与您在 HttpGet 属性中编写的相同,例如
http://localhost:2724/api/Product/Get/myfoo1
如果您确实希望将参数作为 ?fooId=myFoo 传递,那么您需要将您的方法声明为:
[HttpGet("[action]")]
public Foo Get([FromUri]string fooId)
{
...
}
我正在尝试在我的 .net 核心网站中实施基本路由 api。
我有一个这样的控制器:
[Route("api/[controller]")]
public class FooController : Controller
{
//out of the box
[HttpGet("[action]")] //get the list
public IEnumerable<Foo> Get()
{
//omitted
}
//added: request detail request///
[HttpGet("[action]/{fooid}")]
public Foo Get(string fooid)
{
//omitted
}
}
我正在尝试使以下路线有效:
详细信息:
http://localhost:2724/api/Product/Get?fooid=myfoo1
还有一个通用的列表:
http://localhost:2724/api/Product/Get
问题是 ?fooid=
的调用以 IEnumerable
版本结束,我似乎无法正确处理。
我尝试了各种句法变体来克服这个问题,例如:[HttpGet("{fooid}")]
但这似乎没有帮助。
我知道我可以重命名该方法,但我这样做是为了练习。
我也知道索取文件还没有完成,但欢迎就此事提供任何帮助。
我也试过添加路由:
app.UseMvc(routes =>
{
routes.MapRoute( //default
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapRoute(
name: "fooid",
template: "{controller=Home}/{action=Index}/{fooid?}");
routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new { controller = "Home", action = "Index" });
});
我尝试了here中描述的一些方法,但没有成功。
你能告诉我一些方向吗?
您的 URL 参数版本不正确。它需要与您在 HttpGet 属性中编写的相同,例如
http://localhost:2724/api/Product/Get/myfoo1
如果您确实希望将参数作为 ?fooId=myFoo 传递,那么您需要将您的方法声明为:
[HttpGet("[action]")]
public Foo Get([FromUri]string fooId)
{
...
}