Web API 2 方法未找到

Web API 2 method not found

我有一个现有的 WEB 表单(Framework 4.7.2)应用程序,我向其中添加了一个名为 ClaimController

的 Web API

我试图用这个 url /api/claim/Getclaims/2022 调用 webpi 但没有找到。

有什么东西不见了吗?

ClaimController.cs

using System.Net.Http;
using System.Web.Http;
using Dashboard.App_code;

namespace Dashboard.api
{
    public class ClaimController : ApiController
    {    
        
        
        [System.Web.Http.Route("api/Claim/Getclaims/{year?}")]
        [System.Web.Http.HttpGet]
        public IHttpActionResult Getclaims(string year)
        {
            return Ok(ClData.GetClaimsChart(year));
        }
       
    }
}

Global.asax.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.Http;
using System.Web.Routing;

namespace Dashboard
{
    public class Global : System.Web.HttpApplication
    {
        protected void Application_Start(object sender, EventArgs e)
        {
            
            RouteTable.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = System.Web.Http.RouteParameter.Optional }
            );
        }
    }
}

关于您的设置,您需要在 Global.asax.cs 文件中定义路线之前添加 GlobalConfiguration.Configuration.MapHttpAttributeRoutes()

GlobalConfiguration.Configuration.MapHttpAttributeRoutes();

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

GlobalConfiguration.Configuration.EnsureInitialized();