如何解决ASP.NET Core 路由属性路由
我的控制器代码如下所示:
[Route("api/[controller]")]
[ApiController]
public class PaymentDetailController : ControllerBase
{
[HttpGet]
public async Task<string> GetPaymentDetail()
{
return "Success";
}
}
我正在尝试这样访问
http://localhost:47744/api/paymentdetail
http://localhost:47744/api/paymentdetail/GetPaymentDetail
我无法访问我的控制器和方法
解决方法
如果你想使用这样的路线
http://localhost:47744/api/paymentdetail/GetPaymentDetail
你需要这个控制器路由
[Route("api/[controller]/[action]")]
public class PaymentDetailController : ControllerBase
{
[HttpGet]
public async Task<string> GetPaymentDetail()
{
return "Success";
}
}
如果你想使用这样的路线
http://localhost:47744/api/GetPaymentDetail
你需要这个控制器路由
[Route("api/[action]")]
public class PaymentDetailController : ControllerBase
{
[HttpGet]
public async Task<string> GetPaymentDetail()
{
return "Success";
}
}
或者你可以同时使用两条路线
[Route("api/[controller]")]
[ApiController]
public class PaymentDetailController : ControllerBase
{
[Route("~/api/PaymentDetail/GetPaymentDetail")]
[Route("~/api/GetPaymentDetail")]
public async Task<string> GetPaymentDetail()
{
return "Success";
}
}
,
[Route("api/[controller]")]
[ApiController]
public class PaymentDetailController : ControllerBase
{
[HttpGet]
[Route("GetPaymentDetail")]
public async Task<string> GetPaymentDetail()
{
return "Success";
}
}
喜欢吗?
,您的网址指向 /api/paymentdetail
,但您的 ActionMethod 名为 GetPaymentDetail()
。
应该有效的 URL 很可能是 /api/paymentdetail/getpaymentdetail
。
您可能想将您的 ActionMethod 重命名为 Get()
,因为您获取的资源已经很清楚了。
可以使用http://localhost:47744/api/paymentdetail访问,路由会寻找第一个get方法的action。
或者像这样:
[Route("api/[controller]")]
[ApiController]
public class PaymentDetailController : ControllerBase
{
[HttpGet("GetPaymentDetail")]
public async Task<string> GetPaymentDetail()
{
return "Success";
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。