简体   繁体   English

C#WebAPI限制路由

[英]C# webAPI restrict route

in a webapi project's WebAPIConfig.cs, 2 routes are added 在webapi项目的WebAPIConfig.cs中,添加了2条路由

config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

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

I try to create an apiController contains below functions 我尝试创建一个包含以下功能的apiController

[HttpGet]
public string Get(int id)
{
    return "get";
}
[HttpGet]
[ActionName("ByWait")]
public string[] ByWait(int id)
{
    return "bywait";
}

I expects that requesting /api/controllername/1234 returns "get", and requesting /api/controllername/bywait/1234 returns "bywait". 我希望请求/ api / controllername / 1234返回“ get”,而请求/ api / controllername / bywait / 1234返回“ bywait”。

However, the actual result is /api/controllername/1234 >> throw exception Multiple actions were found that match the request /api/controllername/bywait/1234 >> "by wait" 但是,实际结果是/ api / controllername / 1234 >>引发异常找到多个与请求匹配的动作/ api / controllername / bywait / 1234 >>“通过等待”

However can fix the issue? 但是可以解决此问题吗? st how to restrict the function ByWait only accepts request containing action so that it only response to /api/controllername/bywait/1234 and ignore /api/controllername/1234 st如何限制功能ByWait仅接受包含操作的请求,以便仅响应/ api / controllername / bywait / 1234并忽略/ api / controllername / 1234

Or there is other better solution? 还是有其他更好的解决方案?

Thanks 谢谢

First you can change WebApiConfig: 首先,您可以更改WebApiConfig:

config.Routes.MapHttpRoute(
    name: "ActionApi",
    routeTemplate: "api/{controller}/{action}/{id}"
);

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

Then controller: 然后控制器:

[HttpGet]
public string Get()
{
    return "get-default";
}

[HttpGet]
public string Get(int id)
{
    return "get" + id;
}

[HttpGet]
[Route("api/values/bywait/{id}")]
public string ByWait(int id)
{
    return "bywait";
}

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

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