gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:10:45 25 4
gpt4 key购买 nike

我一直在为基于属性路由的 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

关于c# - 为什么这个 webapi2 属性路由不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37909299/

25 4 0
文章推荐: c# - 来自正文空值
文章推荐: Javascript 可以将背景颜色更改为某些
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com