Search code examples
asp.net-mvcapiasp.net-mvc-routing

Calling web API with route attribute using ajax


I have a web API controller

    public class DefaultController : ApiController
{
    [HttpPost]
    public IHttpActionResult PostAction(int id, Student student)
    {
        return Ok("This is message");
    }

}

I can call PostAction method using JQuery

  <script>
    $(document).ready(function() {
        $("#btn").click(function() {
            var obj = { 'name': 'alex' };
            $.ajax({
                    method: "POST",
                    url: '@Url.Action("PostAction","Default",new {id=3,httproute=true})',
                    data: obj
                })
                .done(function(data) {
                    alert("success: " + data);
                })
                .fail(function(xhr, status, error) {
                    alert("error: " + xhr.responseText);
                });
        });
    });
</script>

Generated url is: /api/default/3'

Now if I put routing attribute on controller

    [Route("api/default")]
public class DefaultController : ApiController

how should I call APIs using Url.Action ?


Solution

  • You don't apply the Route attribute to the controller, instead you apply it to an action method.

    Also there is no point in applying an a route pattern which matches with the default route pattern url. But if you are using attribute routing to give a nice url pattern to your action method, you can specify the route name as well which you can use with the HttpRouteUrl helper method.

    public class DefaultController : ApiController
    {
        [HttpPost]
        [Route("api/default2",Name = "MyApi")]
        public IHttpActionResult PostAction(int id, Student student)
        {
            return Ok("This is message");
        }
    }
    

    and in your razor view you can do this.

    <script>
       var url = "@Url.HttpRouteUrl("MyApi", new { id = 3 })";
    </script>