[英]Web API 2 Attribute Routing Not Working in 4.5 WebForms Project
我看到了许多与我的标题相似的其他问题,但似乎没有一个问题是相同的问题或提供我需要的洞察力。
我已将 Web API Controller 添加到现有的旧版 4.5 WebForms 应用程序中,并试图通过对现有代码库的最小更改使其工作。 因此,当您从头开始创建项目时,我没有典型的 static WebApiConfig
class 和其他默认创建的项目。 我现有的代码库是:
全球.asax
protected void Application_Start( Object sender, EventArgs e )
{
GlobalConfiguration.Configure( config =>
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new
{
id = RouteParameter.Optional
}
);
} );
}
Controller
namespace Modeler.Endpoints
{
public class KatAppEndpoints : ApiController
{
[HttpGet]
[Route( "api/katapp/calculations" )]
public IEnumerable<string> GetCalculations()
{
return new string[] { "value1", "value2" };
}
}
}
Javascript
$(document).ready(function() {
$.getJSON("api/katapp/calculations")
.done(function () { debugger; })
.fail(function (_jqXHR, errorStatus, errorMessage) { debugger; })
.always(function () { debugger; });
});
当被调用时,我always
fail
,结果是:
错误状态:“错误”
错误消息:“未找到”
有什么明显的我失踪了吗?
更新
如果相反,我将 Controller 更改为...
namespace Modeler.Endpoints
{
public class KatAppsController : ApiController
{
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
}
和我的 javascript 到:
$.getJSON("api/katapps")
.done(function () { debugger; })
.fail(function (_jqXHR, errorStatus, errorMessage) { debugger; })
.always(function () { debugger; });
事情正常。 但是,我有一些端点并想使用属性,但如果我能弄清楚如何在 url 中获得另一部分(即上面的 /calculations 部分),我可能会放弃它。
不知道为什么,但这条评论指出我在正确的位置: https://stackoverflow.com/a/38130308/166231
因此,即使我想使用属性路由并且可能与 controller 名称不接近,我仍然必须使用*Controller
来结束 class 名称。 将KatAppEndpoints
重命名为KatAppEndpointsController
后,一切正常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.