简体   繁体   中英

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.

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
            }
        );
    } );
}

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; });
});

When called, I hit the fail and always and the result is:

errorStatus: "error"
errorMessage: "Not Found"

Anything obvious I'm missing?

Update

If instead I change my Controller to...

namespace Modeler.Endpoints
{
    public class KatAppsController : ApiController
    {
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }
    }
}

And my javascript to:

$.getJSON("api/katapps")
    .done(function () { debugger; })
    .fail(function (_jqXHR, errorStatus, errorMessage) { debugger; })
    .always(function () { debugger; });

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 (ie the /calculations part from above).

Not sure why, but this comment pointed me in the right spot: https://stackoverflow.com/a/38130308/166231

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM