Reputation: 6029
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
Now I guess it could be to do with the URL I have specified but I'm uncertain any help?
Upvotes: 0
Views: 10964
Reputation: 343
Please note that you need to run your web api project first and it should be kept running. Only then you shall make the ajax call.
In my case the web api controller and the test1.html file are in the same project.
If you web api project is different and your mvc project is different then you are likely to get cross site scripting error.
more info can be found on the below link.
http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
Upvotes: 1
Reputation: 343
I don't have an exact project structure as yours, but i have a perfect working api demo which i had created today.
I am sorry i can't upload the screenshots because i have just started using stackoverflow and i am still a beginner and they aren't allowing me to upload the screenshots yet.
But i hope this will help.
Controller name is Default1 which is under the controller folder. here's the code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using demowebapi1.Models;
namespace demowebapi1.Controllers
{
public class Default1Controller : ApiController
{
public void test1(List<Class1> obj)
{
for(int i=0; i<obj.Count;i++)
{
string s1 = obj[i].text1;
string s2 = obj[i].text2;
}
}
}
}
I have used a list object as a parameter for my action method in the controller. Class1 is my model class which is under the models folder. here's the code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace demowebapi1.Models
{
public class Class1
{
public string text1 { get; set;}
public string text2 {get; set;}
}
}
here's my code for webapiconfig.cs which is in the app_start folder.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace demowebapi1
{
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}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
here's the html file called "test1.html" via which i am making jquery ajax call. Please note that i am using post instead of get.
<html>
<head>
<title> </title>
<script src="jquery-2.1.3.js"></script>
</head>
<body>
<input type="text" id="txt0" /> <input type="text" id="text0" class="tmp" /> <br />
<input type="text" id="txt1" /> <input type="text" id="text1" class="tmp" />
<input type="button" onclick="makepost();" value="click me" />
<script type="text/javascript">
function makepost()
{
var POExpedite = [];
var arr = $(".tmp");
console.log(arr.length);
for(var i=0;i<arr.length; i++)
{
var str1 = $("#txt" + i).val();
alert(str1);
var str2 = $("#text" + i).val();
alert(str2);
POExpedite.push({
"text1": str1,
"text2": str2
});
}
console.log(JSON.stringify(POExpedite));
var apiurl = "http://localhost:4086/api/Default1/test1"
$.ajax({
type: "POST",
contentType: "application/json",
url: apiurl,
data: JSON.stringify(POExpedite),
async: false
});
}
</script>
</body>
</html>
Upvotes: 3