Skip to main content
 首页 » 编程设计

c#之为什么这个 webapi2 属性路由不起作用

2024年02月05日2552php

我一直在为基于属性路由的 WebApi2 设置而苦苦挣扎,但我已经想不出可能是什么问题。以下代码是Visual Studio 2015新创建的WebApi工程,没有改动。它根本不起作用。

响应内容如下:

<Error> 
<Message> 
No HTTP resource was found that matches the request URI 'http://.../services/webapi2/api/dummies/dummymethod'. 
</Message> 
<MessageDetail> 
No type was found that matches the controller named 'dummies'. 
</MessageDetail> 
</Error> 

到目前为止我做了什么:

  • 我检查了文档是否遗漏了什么 - 一切似乎都很好并且适合文档。
  • 我已经检查了这里的可用答案是否找到了有用的东西 - 我已经尝试了我找到的所有东西但没有成功

提前感谢您的帮助!

虚拟 Controller .cs

using System.Web.Http; 
 
namespace WebApi2.Controllers 
{ 
    [RoutePrefix( "Dummies" )] 
    public class Dummy : ApiController 
    { 
        [Route("dummymethod")] 
        public string Get() 
        { 
            return "asdasd"; 
        } 
    } 
} 

WebApiConfig.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web.Http; 
 
namespace WebApi2 
{ 
    public static class WebApiConfig 
    { 
        public static void Register(HttpConfiguration config) 
        { 
            // Web API configuration and services 
 
            // Web API routes 
            config.MapHttpAttributeRoutes(); 
 
            config.Routes.MapHttpRoute( 
                name: "DefaultApi", 
                routeTemplate: "api/{controller}/{id}", 
                defaults: new { id = RouteParameter.Optional } 
            ); 
        } 
    } 
} 

已安装的包:

<?xml version="1.0" encoding="utf-8"?> 
<packages> 
  <package id="Microsoft.AspNet.WebApi" version="5.2.3" targetFramework="net452" /> 
  <package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net452" /> 
  <package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net452" /> 
  <package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.3" targetFramework="net452" /> 
  <package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="1.0.0" targetFramework="net452" /> 
  <package id="Microsoft.Net.Compilers" version="1.0.0" targetFramework="net452" developmentDependency="true" /> 
  <package id="Newtonsoft.Json" version="6.0.4" targetFramework="net452" /> 
</packages> 

请您参考如下方法:

您正在使用路由前缀仅为 dummies 的属性路由,因此它会映射到此 URL

http://.../services/webapi2/dummies/dummymethod 

因此,要么使用上面的 URL,要么更新您的路由前缀以包含 api 以匹配您示例中使用的 URL

namespace WebApi2.Controllers 
{ 
    [RoutePrefix( "api/Dummies" )] 
    public class Dummy : ApiController 
    { 
        //GET api/dummies/dummymethod 
        [HttpGet] 
        [Route("dummymethod")] 
        public string Get() 
        { 
            return "asdasd"; 
        } 
    } 
} 

以上匹配请求URI http://.../services/webapi2/api/dummies/dummymethod