加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 存在多个获取操作时的MVC API路由

发布时间:2020-12-16 06:48:46 所属栏目:asp.Net 来源:网络整理
导读:似乎有一千人在堆栈溢出时询问相同的问题,但似乎没有单一的解决方案来解决这个问题.我要再问一次…… 我有一个API控制器,它具有以下操作: // GET api/Exploitation public HttpResponseMessage Get() { var items = _exploitationRepository.FindAll(); var
似乎有一千人在堆栈溢出时询问相同的问题,但似乎没有单一的解决方案来解决这个问题.我要再问一次……

我有一个API控制器,它具有以下操作:

// GET api/Exploitation
    public HttpResponseMessage Get() {
        var items = _exploitationRepository.FindAll();

        var mappedItems = Mapper.Map<IEnumerable<Exploitation>,IEnumerable<ExploitationView>>(items);

        var response = Request.CreateResponse<IEnumerable<ExploitationView>>(HttpStatusCode.OK,mappedItems);
        response.Headers.Location = new Uri(Url.Link("DefaultApi",new { }));
        return response;
    }

    // GET api/Exploitation/5        
    [HttpGet,ActionName("Get")]
    public HttpResponseMessage Get(int id) {
        var item = _exploitationRepository.FindById(id);
        var mappedItem = Mapper.Map<Exploitation,ExploitationView>(item);

        var response = Request.CreateResponse<ExploitationView>(HttpStatusCode.OK,mappedItem);
        response.Headers.Location = new Uri(Url.Link("DefaultApi",new { id = id }));
        return response;
    }

    // GET api/Exploitation/GetBySongwriterId/5
    [HttpGet,ActionName("GetBySongwriterId")]
    public HttpResponseMessage GetBySongwriterId(int id) {
        var item = _exploitationRepository.Find(e => e.Song.SongWriterSongs.Any(s => s.SongWriterId == id))
                                          .OrderByDescending(e => e.ReleaseDate);
        var mappedItem = Mapper.Map<IEnumerable<Exploitation>,IEnumerable<ExploitationView>>(item);

        var response = Request.CreateResponse<IEnumerable<ExploitationView>>(HttpStatusCode.OK,ActionName("GetBySongId")]
    public HttpResponseMessage GetBySongId(int id) {
        var item = _exploitationRepository.Find(e => e.SongId == id)
                                          .OrderByDescending(e => e.ReleaseDate);
        var mappedItem = Mapper.Map<IEnumerable<Exploitation>,new { id = id }));
        return response;
    }

在我的APIConfig中,我定义了以下路由:

config.Routes.MapHttpRoute(
            name: "DefaultApi",routeTemplate: "api/{controller}/{id}",defaults: new { id = RouteParameter.Optional }
        );

        config.Routes.MapHttpRoute(
            name: "ActionApi",routeTemplate: "api/{controller}/{action}/{id}",defaults: new { id = RouteParameter.Optional,action = RouteParameter.Optional },constraints: new { id = @"d+" }
        );

我发现我可以访问以下操作没问题:
/ API /开发
/ API /开发/ getbysongwriterid / 1
/ API /开发/ getbysongid / 1

当我尝试访问/ api / exploit / 1时,我得到了这个异常

"Multiple actions were found that match the request: System.Net.Http.HttpResponseMessage Get(Int32) on type Songistry.API.ExploitationController System.Net.Http.HttpResponseMessage GetBySongwriterId(Int32)" exception.

谁能看到我的路线出了什么问题?还是错了别的什么?

解决方法

我找到了一个优雅的解决方案.

我修改了我的ApiRouteConfig以具有以下路线:

config.Routes.MapHttpRoute(
            name: "DefaultGetApi",action = "Get" },constraints: new { id = @"d+",httpMethod = new HttpMethodConstraint(HttpMethod.Get) }
        );

        config.Routes.MapHttpRoute(
            name: "DefaultApi",defaults: new { id = RouteParameter.Optional },constraints: new { id = @"d+" }
        );            

        config.Routes.MapHttpRoute(
            name: "ActionApi",action = RouteParameter.Optional }
        );

现在我可以访问:

/api/exploitation
/api/exploitation/1
/api/exploitation/getbysongid/1
/api/exploitation/getbysongwriterid/1

我根本不需要修改我的控制器操作来使用这个新的路由配置.

如果您有多个PUT或POST操作,则可以创建如下所示的新路由:

config.Routes.MapHttpRoute(
        name: "DefaultGetApi",action = "Put" },httpMethod = new HttpMethodConstraint(HttpMethod.Put) }
    );

    config.Routes.MapHttpRoute(
        name: "DefaultGetApi",action = "Delete" },httpMethod = new HttpMethodConstraint(HttpMethod.Delete) }
    );

我希望这个答案对每个人都有帮助,因为这似乎是人们常见的问题.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读