Hello I've started to learn Web API's I currently have a Web Api Controller located at the root of my project (not in a folder) as shown here

  public class LearnWebApi : ApiController
  {
    // GET api/<controller>
    public IEnumerable<string> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // GET api/<controller>/5
    public string Get(int id)
    {
        return "value";
    }

    // POST api/<controller>
    public void Post([FromBody]string value)
    {
    }

    // PUT api/<controller>/5
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/<controller>/5
    public void Delete(int id)
    {
    }
  }

Now I have a home controller which lived inside the controllers folder and the view lives inside the view folder. now on the view I have a button, when I click this button I want to make a call to the Api Web Controller Get Method and pass in a ID of 2 for example I have placed a break point on the following

// GET api/<controller>/5
public string Get(int id)
{
    return "value";
}

But it doesn't get hit, instead I get the messages in the browser saying

404 Not Found - http://localhost:27774/~/api/LearnWebApi/Get/5"

My jquery is here

<h2>Index</h2>
<button id="PressMe">Press me</button>

<script type="text/javascript">
$(document).ready(function () {

    $('#PressMe').click(function () {
        $.ajax({
            type: "POST",
            dataType: "json",
            // data: source,
            url: '~/api/LearnWebApi/Get/5', // url of Api controller not mvc
            success: function (data) {
                alert("Redirect true !");

            },
            error: function () {
                alert('erere');
            }

        });

        return false;

    });

});
</script>

This is my WebApiConfig

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

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

Below is how my project is constructed

enter image description here Now I guess it could be to do with the URL I have specified but I'm uncertain any help?

Related posts

Recent Viewed