簡體   English   中英

Web API 2 屬性路由在 4.5 WebForms 項目中不起作用

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM