无法在单个控制器中运行多个GET方法

时间:2017-09-26 12:34:54

标签: mysql asp.net-mvc rest visual-studio-2015 asp.net-web-api2

我使用WEB API数据库在visual studio 2015中创建了MySQL。我有三种GET方法。一个是给出所有数据,第二个给出基于ID的结果,第三个给出基于序列号的结果。前两种方法是完美的,但最后一种方法不是。我还在解决方案中添加了多个路由。以下是我的代码

WebApiConfig

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



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

控制器

 public HttpResponseMessage Get()
    {
        try
        {
            return Request.CreateResponse(HttpStatusCode.Found, mEntities.meters_info_dev.ToList());
        }
        catch (Exception ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
        }
    }


    // GET by ID
    public HttpResponseMessage GetByID(int id)
    {
        try
        {
            return Request.CreateResponse(HttpStatusCode.Found, mEntities.meters_info_dev.SingleOrDefault(m => m.id == id));
        }
        catch (Exception ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
        }
    }


    // GET by serial number
    public HttpResponseMessage GetByMsn(string msn)
    {
        try
        {
            return Request.CreateResponse(HttpStatusCode.Found, mEntities.meters_info_dev.SingleOrDefault(m=> m.meter_msn == msn));
        }
        catch
        {
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, "No Data found");
        }
    }

GetByMsn是无效的。我试图改变路线,但结果仍然相同。给出的solution 1solution 2对我不起作用。

任何帮助都将受到高度赞赏。

1 个答案:

答案 0 :(得分:0)

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

在上面,约束是字母的,我只是将它改为@"^[0-9]+$",它开始为我工作。