Web API 2 属性路由在 4.5 WebForms 项目中不起作用 [英] Web API 2 Attribute Routing Not Working in 4.5 WebForms Project
问题描述
我看到了许多与我的标题相似的其他问题,但似乎没有一个是我需要的相同问题或提供的见解.
I've seen many other questions that are similar to my title but none seem to be same issue or supply insight that I need.
我已将 Web API 控制器添加到现有的旧版 4.5 WebForms 应用程序中,并尝试在对现有代码库进行最少更改的情况下使其工作.因此,当您从头开始创建项目时,我没有典型的静态 WebApiConfig
类和其他默认创建的项目.我现有的代码库是:
I've added a Web API Controller to an existing, legacy 4.5 WebForms application and am trying to get it working with minimal changes to existing code base. So I don't have the typical static WebApiConfig
class and other default created items when you create project from scratch. My existing code base is:
Global.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
}
);
} );
}
控制器
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; });
});
调用时,我点击了fail
和always
,结果是:
When called, I hit the fail
and always
and the result is:
错误状态:错误"
错误消息:未找到"
errorStatus: "error"
errorMessage: "Not Found"
有什么明显我遗漏的地方吗?
Anything obvious I'm missing?
更新
如果相反,我将控制器更改为...
If instead I change my Controller to...
namespace Modeler.Endpoints
{
public class KatAppsController : ApiController
{
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
}
我的 javascript 到:
And my javascript to:
$.getJSON("api/katapps")
.done(function () { debugger; })
.fail(function (_jqXHR, errorStatus, errorMessage) { debugger; })
.always(function () { debugger; });
一切正常.但是,我有一些端点并想使用属性,但如果我能弄清楚如何在 url 中获取另一部分(即上面的/calculations 部分),也许我会放弃它.
Things work correctly. However, I have a handful of endpoints and wanted to use Attributes, but maybe I'll give up on that if I can figure out how to get another portion in the url (i.e. the /calculations part from above).
推荐答案
不知道为什么,但这条评论指出了我正确的位置:https://stackoverflow.com/a/38130308/166231
Not sure why, but this comment pointed me in the right spot: https://stackoverflow.com/a/38130308/166231
所以即使我想使用属性路由并且可能不接近控制器名称是什么,我仍然必须以 *Controller
结束类名.将 KatAppEndpoints
重命名为 KatAppEndpointsController
后,一切正常.
So even though I want to use attribute routing and might not be close to what controller name is, I still have to end the class name with *Controller
. After renaming KatAppEndpoints
to KatAppEndpointsController
, everything worked.
这篇关于Web API 2 属性路由在 4.5 WebForms 项目中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!