webapi控制器调用错误的方法 [英] webapi controller calling wrong method

查看:231
本文介绍了webapi控制器调用错误的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经使用c#和webApi 2.0实现了通用控制器

I have implemented a generic controller using c# and webApi 2.0

http://localhost:4200/api/projects 将正确调用GetAllItems()并返回预期结果

http://localhost:4200/api/projects will correctly call GetAllItems() and return the expected results

http://localhost:4200/api/projects/1 不调用GetItemById() 而是调用GetAllItems()

http://localhost:4200/api/projects/1 does not call GetItemById( ) Instead, it calls GetAllItems( )

在构建泛型之前,我为项目构建了具体的控制器. 它是剪切/粘贴,并调用正确的方法. 我的想法是我的路线在泛型上是错误的,或者因为它是泛型而应该有所不同,但是我似乎并没有提出正确的语法.

prior to building the generic, i built a concrete controller for projects. Its a cut/paste and it calls the correct methods. My thinking is that my route is wrong on the generic, or should be different because it is a generic, but I can not seem to come up w/ the correct syntax.

当URL包含尾随整数时,为什么泛型不调用正确的方法?

重新排序方法

将动词增强为System.Web.Http.HttpGet

Enhancing the verb to be System.Web.Http.HttpGet

将GET和ROUTE组合到1个标记中,以逗号分隔

Combining GET and ROUTE into 1 tag, comma separated

在函数签名中的itemId参数上指定[FromUri]

Specifying [FromUri] on the itemId parameter in the function signature

注释GetAllItems()->所请求的资源不支持http方法GET(这可能是个大提示,但是对我来说却是生命……)

Commenting out the GetAllItems() --> The requested resource does not support http method 'GET' (This has to be the big clue, but for the life of me...)

这是通用模板的缩写列表

Here is an abbreviated listing of the generic template

    [RoutePrefix("api/{contoller}")]
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public class baseController<T, T_Q > : ApiController 
                where T:pgBaseClass, new()
                where T_Q : sbQuery<T> , new()
                 
    {

        

        [HttpGet]
        [Route("")]
        public CustomJsonStringResult GetAllItems()
        {
            T_Q q = new T_Q();
            List<T> l = q.Items();


            string json = q.ListToJSON(l);

            return JSONStringResultExtension.JSONString(this, json, HttpStatusCode.OK);
        }


        [HttpGet]
        [Route("{itemId:int}")]
        public IHttpActionResult GetItemById(int itemId)
        {
            T_Q q = new T_Q();
            T p = q.GetById(itemId);

            if (p == null)
            {
                return JSONStringResultExtension.JSONString(this, "Item not Found", HttpStatusCode.NotFound);
            }
            else
            {
                return JSONStringResultExtension.JSONString(this, p.JSON, HttpStatusCode.OK);
            }
        }
}

这是使用通用名称的项目控制器的定义

Here is the definition for the projects controller using the generic

  public class ProjectsController : baseController<pgProject,pgProjectQuery>
    {
  }

这是按预期工作的非通用控制器的缩写列表. (我不排除其中一个使项目能够编译和运行...)

Here is an abbreviated listing of the non generic controller that works as expected. (I am excluding one or the other to get the project to compile and run...)

 [RoutePrefix("api/projects")]
    [EnableCors(origins: "*", headers: "*", methods: "*")]
    public class  ProjectController : ApiController
    {

        //[HttpGet]
        [Route("")]
        public CustomJsonStringResult GetAllItems()
        {
            pgProjectQuery ag = new pgProjectQuery();
            ag.SortExpression = " [Name] asc ";
            List<pgProject> l = ag.Items();


            string json = ag.ListToJSON(l);

            return JSONStringResultExtension.JSONString(this, json, HttpStatusCode.OK);
        }

        

        [HttpGet]
        [Route("{itemId:int}")]
        public IHttpActionResult GetItemById(int itemId)
        {
            pgProjectQuery q = new pgProjectQuery();
            pgProject p = q.GetById(itemId);
            
            if (p == null)
            {
                return JSONStringResultExtension.JSONString(this, "Item not Found", HttpStatusCode.NotFound);
            }
            else
            {
                return JSONStringResultExtension.JSONString(this, p.JSON, HttpStatusCode.OK);
            }
        }
}

推荐答案

我在webApiConfig.js中配置了此

I had this configured in webApiConfig.js

在这里,我定义了唯一的路由,并带有一个称为id的可选参数. 我在我的GetItemById()方法中更改了参数名称,这可行.

here i have the sole route defined w/ an optional parameter called id. I changed the parameter name in my GetItemById() method and this works.

公共静态无效寄存器(HttpConfiguration配置) { //Web API配置和服务

public static void Register(HttpConfiguration config) { // Web API configuration and services

    // Web API routes
    config.MapHttpAttributeRoutes();

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

}


  [System.Web.Http.HttpGet]
        [Route("{id:int}")]
        public CustomJsonStringResult GetItemById([FromUri] int id){...}

我无法解释的是为什么非通用控制器能够按预期工作,而基于通用控制器却无法正常工作. 我确实相信现在情况可能更正确",只是希望我有一个事实的答案. 我的补丁方法也遇到了同样的问题.将参数重命名为id即可.

What I can not explain is why the non generic controller worked as expected but the generic-based controller does not. I do believe things are probably 'more correct' now, just wish I had a factual answer. I also ran into the same problem with my patch method. Renamed the parameter to id and it worked.

希望这可以帮助某人.

这篇关于webapi控制器调用错误的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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