How to add custom methods to ASP.NET WebAPI controller?

后端 未结 4 1417
悲&欢浪女
悲&欢浪女 2020-12-14 01:52

In ASP.NET MVC WebAPI project by default we have created following controller

 public class ValuesController : ApiController
    {
        /         


        
4条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-14 02:14

    First Put this route to webapiconfig.cs

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

    Now you can add actions to your controllers like this

     [HttpPost]
        public void Upload()
        {
               //Do some thing
        }
    

    I decorated upload action with httppost attribute that means this action accept just only post requests , if you want to actions to be GET , you can remove attribute or just decorate to your suite

提交回复
热议问题