【问题标题】:ASP.NET Core route attribute routingASP.NET Core 路由属性路由
【发布时间】:2021-09-04 14:47:18
【问题描述】:

我的控制器代码如下所示:

[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

我无法访问我的控制器和方法

【问题讨论】:

  • paymentdetailcontroller 的名称 - GetPaymentDetail 是操作方法 - 根据需要组合成完整的 URL /api/paymentdetail/GetPaymentDetail - 所以是什么问题或疑问,真的???

标签: c# asp.net-core .net-core routes attributerouting


【解决方案1】:

您的 URL 指向 /api/paymentdetail,但您的 ActionMethod 称为 GetPaymentDetail()

应该工作的 URL 很可能是 /api/paymentdetail/getpaymentdetail

您可能希望将您的 ActionMethod 重命名为 Get(),因为您已经清楚您将获得什么资源。

【讨论】:

  • paymentdetail控制器 的名称 - GetPaymentDetail 是操作方法 - 根据需要组合成完整的 URL /api/paymentdetail/GetPaymentDetail ..
  • 忽略了原始帖子中的第二个 URL。你说的对。第二个 URL 应该可以工作。
【解决方案2】:
[Route("api/[controller]")]
[ApiController]
public class PaymentDetailController : ControllerBase
{   
    [HttpGet]
    [Route("GetPaymentDetail")]
    public async Task<string> GetPaymentDetail()
    {
        return "Success";
    }
}

像这样?

【讨论】:

  • 由于方法名称已经是GetPaymentDetail,我看不出这有什么帮助.... URL 将完全相同...
  • 感谢您帮助我,但这行代码对我不起作用。
【解决方案3】:

如果你想使用这样的路线

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";
    }
}

【讨论】:

    【解决方案4】:

    可以使用http://localhost:47744/api/paymentdetail访问,路由会寻找第一个get方法的动作。

    或者这样:

    [Route("api/[controller]")]
        [ApiController]
        public class PaymentDetailController : ControllerBase
        { 
    
          [HttpGet("GetPaymentDetail")]
    
            public async Task<string> GetPaymentDetail()
            {
                return "Success";
            }
          
    

    【讨论】:

    • 能否分享startup.cs类代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-01
    相关资源
    最近更新 更多