网页API路由在ASP.NET MVC 4倍Get方法 [英] Web Api Routing for multiple Get methods in ASP.NET MVC 4

查看:85
本文介绍了网页API路由在ASP.NET MVC 4倍Get方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的Web API和ASP.NET MVC的,我是很新的吧。我已经通过asp.net网站上的一些演示了,我试图做到以下几点。

I am using Web Api with ASP.NET MVC, and I am very new to it. I have gone through some demo on asp.net website and I am trying to do the following.

我有4个get方法,具有以下签名

I have 4 get methods, with the following signatures

public List<Customer> Get()
{
//gets all customer
}

public List<Customer> GetCustomerByCurrentMonth()
{
//gets some customer on some logic
}

public Customer GetCustomerById(string id)
{
//gets a single customer using id
}

public Customer GetCustomerByUsername(string username)
{
//gets a single customer using username
}

有关上述所有我的方法,希望有我的web API有点像如下图所示。

For all the methods above I would like to have my web api somewhat like as shown below


  • 列表获取()= API /客户/

  • 客户GetCustomerById(字符串ID)= API /客户/ 13

  • 列表GetCustomerByCurrentMonth()= /客户/ currentMonth

  • 客户GetCustomerByUsername(用户名字符串)= /客户/ customerByUsername /亚西尔·

  • List Get() = api/customers/
  • Customer GetCustomerById(string Id) = api/customers/13
  • List GetCustomerByCurrentMonth() = /customers/currentMonth
  • Customer GetCustomerByUsername(string username) = /customers/customerByUsername/yasser

我试图使更改路由,但因为我是新来的吧,could'nt明白了。

I tried making changes to routing, but as I am new to it, could'nt understand much.

所以,请一定能够一个可以帮助我了解和指导我应该怎么做。谢谢

So, please can some one help me understand and guide me on how this should be done. Thanks

推荐答案

从这里的路由在Asp.net的mvc 4和网页API

达林季米特洛夫 已经发布这是工作对我来说是很好的答案。

Darin Dimitrov has posted a very good answer which is working for me.

它说...

您可以有两个途径:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.Routes.MapHttpRoute(
            name: "ApiById",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional },
            constraints: new { id = @"^[0-9]+$" }
        );

        config.Routes.MapHttpRoute(
            name: "ApiByName",
            routeTemplate: "api/{controller}/{action}/{name}",
            defaults: null,
            constraints: new { name = @"^[a-z]+$" }
        );

        config.Routes.MapHttpRoute(
            name: "ApiByAction",
            routeTemplate: "api/{controller}/{action}",
            defaults: new { action = "Get" }
        );
    }
}

这篇关于网页API路由在ASP.NET MVC 4倍Get方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆