简体   繁体   中英

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

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

This works fine for this api end point.

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

But I want to use any meaningful name for the variable instead of 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.

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

Example:

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

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