0

I am using web api in my mvc application. I have a problem while calling web api using jquey.get function. Consider the following scenario:

I have 2 controller name:

  1. HomeMVCController
  2. TestAPIController (using mvc style routing i.e. api/{controller}/{action}/{id})

HomeMVC controller contains 2 actions

  1. Index
  2. About

TestAPI controller contains 1 action

  1. Get

When i was on Index view of HomeMVC controller i.e.

http://localhost:1025/Home

and when i call $.get("api/TestAPI/Get") from the browser it returns the expected json response.

But when i was on About view of HomeMVC controller i.e.

http://localhost:1025/Home/About

and when i call $.get("api/TestAPI/Get") from the browser it returns error, resource not found, and the resource it is trying to locate is:

http://localhost:1025/Home/About/api/TestAPI/Get  

instead of

http://localhost:1025/api/TestAPI/Get  

Why browser added Home/About in the url to api and why it is not added Home/Index when i was on Index view. On Index view why api call is working as expected and why not working on About view ??

1 Answer 1

1

You used a relative url when you should be using an absolute url.

You should instead use an absolute url by doing:

$.get("@Url.RouteUrl("@Url.RouteUrl("DefaultApi", new {httproute="", controller="TestAPI", action="Get"}))

If you want to keep your javascript in separate js files (and not in the razor files) what you can do is have an initialize method that is called from a razor view.

The .js file:

var myPageJsUrls = {};

var MyPageInitialize = function(getItemsUrl, saveItemUrl, editItemUrl){
    myPageJsUrls.getItemsUrl = getItemsUrl;
    myPageJsUrls.saveItemUrl = saveItemUrl;
    myPageJsUrls.editItemUrl = editItemUrl;
}


var getItems = function(){
    return $.get(myPageUrls.getItemsUrl);
}

...

In the razor file:

<script>
    myPageInitialize('@Url.Action("AllItems", "Items")', '@Url.RouteUrl("DefaultApi", new {httproute="", controller="TestAPI"}, ...)
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

but you are using server syntax for generating absolute url, how i can using this in js file ??
What I usually do is I have an Initialize method that is called from a Razor view and with all the urls the javascript needs, e.g.: Initialize({testApiGet: '@Url.RouteUrl(...)', GetItems: '@Url.Action(...)'}). I'll update the answer with an example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.