Click here to Skip to main content
15,311,561 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My WebApi file contains;
public static void Register(HttpConfiguration config)
{
    // Web API routes
    config.MapHttpAttributeRoutes();

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


I'm making an ajax call;
<script>
    $(document).ready(function () {
        $("#grid").bootgrid();

        //onclick event handler to retrieve row info
        $("#grid").on("click.rs.jquery.bootgrid", function (e, columns, row) {
            url = 'api/AdminContentApi/' + row.Name;

            $.ajax({
                url: url,
                type: 'GET',
                success: function (d) {
                    //Do my stuff here!
                },
                error: function (xhr, textStatus, errorThrown) {
                    alert("Error in operation");
                }
            });
        });
    });
</script>

and finally my Controller code;
    [Authorize(Roles = "Admin")]
    public class AdminContentApiController : ApiController
    {
        [HttpGet]
        public IHttpActionResult GetContentDetail(string name)
        {
            content c = ContentRepository.GetContentByName(name);
            if (c == null)
            {
                return NotFound();
            }
            return Ok(c);
        }
    }
}

My question and the problem is that when the call is envoked I would expect the url to be: api/AdminConTentApi/HOME_1
instead I'm getting; /AdminContent/api/AdminContentApi/HOME_L

Where/How/Why/WTF is it prefixing the url with AdminContent?

Thanks

What I have tried:

According to all the tuts I've read I am doing it correctly but have been working for hours on this problem and have tried everything that tuts described.
Posted
Updated 30-Jan-17 9:01am
v2

1 solution

Your AJAX call is specifying a relative URL. That will be resolved relative to the URL of the current page, not relative to the site.

Assuming that script is inline within the view, try using the HttpRouteUrl helper:
JavaScript
var url = '@Url.HttpRouteUrl("DefaultApi", new { controller = "AdminContentApi" })?name=' + row.name;

WebAPI Tip #5: Generating Links[^]
   
v3
Comments
Mike Hankey 30-Jan-17 15:35pm
   
Mr. Deeming you are the man. I had to modify what you provided but you got me on the right track.
FFR (For Future Reference) this worked for me!
'@Url.HttpRouteUrl("DefaultApi", new { controller = "AdminContentApi" })?name=' + row.name;

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900