简体   繁体   English

如何在webapi c#中配置路由,以便可以使用任何变量名代替{id}

[英]how to configure route in webapi c#, so that any variable name can be used in place of {id}

I have configured the convention based routing as below in WebApiConfig.cs 我已经在WebApiConfig.cs配置了基于约定的路由

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

This works fine for this api end point. 对于此api端点,这工作正常。

[ActionName("DeleteDataDictionary")]
public void DeleteDataDictionary(int id)
{
    //my code
}

But I want to use any meaningful name for the variable instead of id. 但是我想对变量使用任何有意义的名称,而不要使用id。
For example: 例如:

[ActionName("DeleteDataDictionary")]
public void DeleteDataDictionary(int dataDictionaryId)
{
    //my code
}

[ActionName("DeleteMenu")]
public void DeleteMenu(int menuId)
{
    //my code
}

The problem is it only works when I give parameter name as id. 问题是它仅在我将参数名称指定为id时才有效。

Use an attribute routing instead. 请改用属性路由。

[Route("api/delete-dictionary/{dataDictionaryId:int}")]
public void DeleteDataDictionary(int dataDictionaryId)
{
    //my code
}

And send a request as follows, 并发送如下请求,

/api/delete-dictionary/1

Try using the FromRouteAttribute 尝试使用FromRouteAttribute

Example: 例:

[ActionName("DeleteDataDictionary")]
public void DeleteDataDictionary( [FromRoute("id")] int dataDictionaryId)
{
    // your code
}

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

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