【问题标题】:ASP.NET Routing problems when ii have same methods name with different paramsii 具有不同参数的相同方法名称时的 ASP.NET 路由问题
【发布时间】:2018-11-04 00:55:58
【问题描述】:

因为我创建了“BaseController”,所以我遇到了路由问题。 我只使用 4 种方法名称 GET、POST、PUT、DELETE,从前端进行最简单的调用。 所以,当我有这个控制器时:

 [RoutePrefix("api/Router")]
public class RouterController : WifiBaseController
{
    UnitOfWork unitOfWork = new UnitOfWork();

    [JwtAuthentication]
    [HttpGet]
    [Route("")]
    public List<RouterDTO> Get()
    {
        List<router> routerx = unitOfWork.RouterRepository.Get(r => r.IsDeleted == false).ToList();
        List<RouterDTO> routerDTO = Mapper.Map<List<RouterDTO>>(routerx);
        foreach (var router in routerDTO.Where(x => x.Password != ""))
        {
            router.Password = null;
        }
        return routerDTO;
    }

    [HttpGet]
    [JwtAuthentication]
    [Route("{latitude}/{longitude}")]
    public List<RouterDTO> Get(double latitude, double longitude)
    {
        List<RouterDTO> routersDTO = new List<RouterDTO>();
        List<router> routers = new List<router>();

        var myLocation = GPSCalculation.CreatePoint(latitude, longitude);
        routers = unitOfWork.RouterRepository.Get(x => x.Location.Location.Distance(myLocation) < 2000 && x.IsDeleted == false).ToList();

        Mapper.Map(routers, routersDTO);
        foreach (var router in routersDTO.Where(x => x.Password != ""))
        {
            router.Password = "";
        }
        return routersDTO;
    }

我打了这个电话:

http://localhost:50919/api/Router?latitude=46.767&amp;longitude=23.60

首先调用它的方法...为什么?

如果我注释第一个方法,API 会返回:

405 Method Not Allowed(请求的资源不支持http方法'GET')

【问题讨论】:

    标签: c# asp.net-mvc asp.net-web-api asp.net-web-api-routing


    【解决方案1】:

    根据你在第二种方法中的路由属性:

    [Route("{latitude}/{longitude}")]
    

    使用此路由的正确调用看起来应该是:

    http://localhost:50919/api/Router/46.767/23.60
    

    【讨论】:

    • 在我将属性更改为 [Route("{latitude}&{longitude}")] 后,仍然无法正常工作。返回相同的错误.. :(
    • @DavidPantea,你读过答案吗?它是/(正斜杠),而不是&amp;。但这会导致Dots in URL causes 404 with ASP.NET mvc and IIS
    • @StephenMuecke,我想保持这种格式来调用“...Routers?latitude=46.767&longitude=23.60”。有可能吗?
    • @DavidPantea 如果您确实想要该 url,那么它将匹配您的第一个 public List&lt;RouterDTO&gt; Get() 方法(因为 url 不包含 latitudelongitude 的路由段 - 仅查询字符串值) .您需要修改第一种方法以检查查询字符串值是否存在(或不存在),然后有条件地调用 if/else 块中的相关代码部分
    猜你喜欢
    • 2017-05-27
    • 1970-01-01
    • 2016-01-22
    • 2016-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    相关资源
    最近更新 更多