简体   繁体   English

ASP.NET Web API 2自定义路由到特定方法

[英]ASP.NET Web API 2 custom routing to specific method

How can I configure routing in ASP.NET Web API to route it to specific method in controller with GET method? 如何在ASP.NET Web API中配置路由以使用GET方法将其路由到控制器中的特定方法?

http://mysite/healthcheck http:// mysite / healthcheck

Registration in WebAPiConfig looks like this: WebAPiConfig中的注册如下所示:

    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "HealthCheck",
        routeTemplate: "healthcheck",
        defaults: new { action =" DefaultAction" }
    );

The controller looks like this: 控制器如下所示:

[RoutePrefix("healthcheck")]
public class HealthCheckController : ApiController
{
    [HttpGet]
    [ActionName("DefaultAction")]
    public HttpResponseMessage GetHealthCheckStatus()
    {
        return Request.CreateResponse(HttpStatusCode.OK);
    }    
}

I get Not Found instead of Ok when hitting that URL. 击中该URL时,我得到Not Found而不是Ok。 Any help would be appreciated 任何帮助,将不胜感激

UPDATE Thank you for all the suggestions, I checked them all and none works. 更新谢谢您的所有建议,我都检查了所有建议,但没有任何效果。 The route debugger shows no matches. 路由调试器未显示匹配项。 I am putting this on hold for a while. 我暂时搁置一会儿。

In your Startup.cs register attribute routes: 在您的Startup.cs注册属性路由:

config.MapHttpAttributeRoutes();

And in the controller: 并在控制器中:

[RoutePrefix("healthcheck")]
public class HealthCheckController : ApiController
{
    [HttpGet]
    [Route]
    public IHttpActionResult GetHealthCheckStatus()
    {
        return Ok();
    }
}

Remove this in config 在配置中删除它

config.Routes.MapHttpRoute(
    name: "HealthCheck",
    routeTemplate: "healthcheck",
    defaults: new { action =" DefaultAction" }
);

and do this in controller 并在控制器中执行此操作

public class HealthCheckController : ApiController
{
    [AcceptVerbs("GET")]
    [Route("healthcheck")]
    public HttpResponseMessage GetHealthCheckStatus()
    {
        return Request.CreateResponse(HttpStatusCode.OK);
    }
}

I haven't tested it for web-api, but tested it for MVC, I think it should work the same. 我尚未针对Web-api测试过它,但针对MVC进行过测试,我认为它应该可以正常工作。

In route registration you should ensure, that this route comes before the standard api route, because route order matters: 在路由注册中,您应确保此路由位于标准api路由之前,因为路由顺序很重要:

public static void RegisterRoutes(RouteCollection routes) {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "HealthCheck",
            "healthcheck",
            new {Controller = "Default", action = "Index"}
        );

        routes.MapRoute(
            "Default",
            "{controller}/{action}/{id}",
            new {
                controller = "Home",
                action = "Index",
                id = UrlParameter.Optional
            }
        );
    }

In the controller you may not prefix the controllers and action names, but to specify correct controller name and action name in the template: 在控制器中,您可能不会在控制器和操作名称前添加前缀,但要在模板中指定正确的控制器名称和操作名称:

public class DefaultController : Controller
{

    [HttpGet]
    public ActionResult Index()
    {
        return Content("I'm hit");
    }
}

If you still having problems, then you can read this article and enable route debugging too see which route is invoked and what are the params. 如果仍然有问题,则可以阅读本文并启用路由调试,还可以查看调用了哪条路由以及哪些参数。

Since you are enabling attribute routing, you can specify the action as the default endpoint for the controller using RoutePrefix by using [Route("")] with empty route template. 由于启用了属性路由,因此可以通过将[Route("")]与空路由模板一起使用,使用RoutePrefix将操作指定为控制器的默认端点。

[RoutePrefix("healthcheck")]
public class HealthCheckController : ApiController {
    [HttpGet]
    [Route("")] // Matches GET http://mysite/healthcheck
    public IHttpActionResult GetHealthCheckStatus() {
        return Ok();
    }
}

With the above then there would be no need for the convention-based HealthCheck route from the OP. 有了上面的内容,就不需要来自OP的基于约定的HealthCheck路由。 It can be removed safely from WebApiConfig 可以从WebApiConfig安全删除它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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