简体   繁体   中英

Web API Attribute routing in Sitecore 8.1 not working

As Atrribute routing does not work in sitecore 8.1 out of the box, I am following https://github.com/Krusen/Sitecore.WebApi
And got the uget package for Krusen.Sitecore.WebApi.Custom .

This is my ConfigureWebApi class

public class ConfigureWebApi
{
    public void Process(PipelineArgs args)
    {

        GlobalConfiguration.Configure(config => config.Routes.MapHttpRoute(
                name: "myApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            ));
        GlobalConfiguration.Configure(config => config.MapHttpAttributeRoutes());
        GlobalConfiguration.Configure(ReplaceControllerSelector);
    }

    private static void ReplaceControllerSelector(HttpConfiguration config)
    {
        config.Services.Replace(typeof (IHttpControllerSelector),
            new CustomHttpControllerSelector(config, new NamespaceQualifiedUniqueNameGenerator()));
    }
}

And this is my controller

[RoutePrefix("windows")]
public class WmsController : ApiController
{
    [HttpGet]
    [Route("hi")]
    public IHttpActionResult Hello()
    {
        return Ok("Welcome to my Api.");
    }

}

When I call this:

http://my.api.local/api/wms/hello

works.
But when I call

http://my.api.local/api/windows/hi

does not work. It says 404.

Am I missing something !!

The second call is not working because Attribute routing must be configured before Convention-based routes to avoid route conflicts.

public void Process(PipelineArgs args) {
    GlobalConfiguration.Configure(config => {
        // Map Attribute Routes
        config.MapHttpAttributeRoutes();

        // Map Convention-based Routes
        config.Routes.MapHttpRoute(
            name: "myApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        // Replace IHttpControllerSelector with our custom implementation
        ReplaceControllerSelector(config);
    });
}

Which I also believe is how it was shown in the documentation in the linked repo

Secondly based on the RoutePrefix("window") and Route("hi") in the ApiController the mapped attribute route would be mapped as

http://my.api.local/windows/hi 

To get http://my.api.local/api/windows/hi to map to the desired action you would need to update the route prefix as already explained in one of the other answers.

You need to add "api/" into your controller attribute routing

[RoutePrefix("api/windows")]
public class WmsController : ApiController
{
    [HttpGet]
    [Route("hi")]
    public IHttpActionResult Hello()
    {
        return Ok("Welcome to my Api.");
    }

}

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