AJAX call can't find my WebAPI Controller - ajax

I have the following AJAX call:
var params = {
provider: "facebook"
};
$.ajax({
url: "http://localhost/taskpro/api/account/ExternalLogin",
data: JSON.stringify(params),
type: "POST",
contentType: 'application/json; charset=utf-8'
})
.done(function (response) {
alert("Success");
});
calling the following WebAPI controller:
public class AccountController : ApiController
{
[HttpPost]
[AllowAnonymous]
public bool ExternalLogin(string provider)
{
return true;
}
}
with the following routemap:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
When I execute this, fiddler is returning:
{"Message":"No HTTP resource was found that matches the request URI
'http://localhost/taskpro/api/account/ExternalLogin'.","MessageDetail":
"No action was found on the controller 'Account' that matches the request."}
I have several other calls being made to this controller that are working just fine. It's just THIS call that is giving me troubles.
Also, if I remove the parameter in the controller so it's just
public bool ExternalLogin()
and comment out the data line in the ajax, it works fine.
Any ideas why the routing is not working for this call?

I ran across this article:
http://encosia.com/using-jquery-to-post-frombody-parameters-to-web-api/
Basically, WebAPI can't bind to primitive data types like string. You have to either create a model to bind to, or use the [FromBody] attribute. I modified my method to this:
public bool ExternalLogin([FromBody]string provider)
and it's working fine now.

Related

MVC Web Api call from Ajax responds with 404

I know this has been asked dozens of times but I'm really frustrated as none of the suggestions I can find out there work for me and I'm really stuck.
My problem is I'm not being able to call a Web Api from ajax, no matter what configurations/combinations/whatever of routes and everything I try, none of them works and I just get 404.
This is my Global.asax file:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
GlobalConfiguration.Configure(WebApiConfig.Register);
}
This is my WebApiConfig.cs in App_Start folder:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
This is my UserController class:
public class UserController : ApiController
{
public IHttpActionResult GetUserDataById(string id)
{
Clients jsonData = Http.downloadJsonData<Clients>(InsuranceGlobal.clientsUrl);
Client user = jsonData.clients.Where(u => u.id == id).FirstOrDefault();
return Ok(user);
}
}
This is my Ajax call inside cshtml javascript section:
$("#btnGetUserById").click(function () {
$('#userByName').empty();
$("#gettingByIdMsg").text(" Getting User...");
$.ajax({
url: '../api/User',
type: "GET",
contentType: "application/json",
dataType: "json",
data: { id: $("#userId").val() },
success: function (data) {
$('<tr>', { html: formatItem(data) }).appendTo($('#userByName'));
$("#usersTable").removeClass("hidden");
$("#gettingByIdMsg").text("");
},
fail: function (jqXHR, textStatus) {
$("#gettingByIdMsg").text("Request failed: " + textStatus);
}
});
});
I tried GET as well as POST with the [HttpPost] decorator with no avail.
I guess I have all necessary Web Api NuGet packages installed and the app compiles without errors but web api is not being called.
Please help.
Edit 1:
I have to mention that -on purpose- I haven't started a new project with WebApi template in Visual Studio, instead I started a MVC project and then installed all NuGet WebApi necessary packages and configuration (maybe I missed something, don't know).
Ok, after solving my issue I'll answer my own question.
First of all I have to say thanks for all the replies. Love this community and people is very nice here.
After diving into depths of sea... err my solution configuration and fighting a lot with it I remembered I've previously installed WebApi.Owin package and just to try I decided to uninstall it leaving only AspNet.WebApi and voilá, now the WebApi calls are working.
I hope all this effort will help anyone else having a similar issue in the future.
Change
EDIT: based on comment
[RoutePrefix("api/User")]
public class UserController : ApiController
{
[Route("getbyid/{id}")]
public IHttpActionResult GetUserDataById(string id)
{
Clients jsonData = Http.downloadJsonData<Clients> InsuranceGlobal.clientsUrl);
Client user = jsonData.clients.Where(u => u.id ==
id).FirstOrDefault();
return Ok(user);
}
}
and client to
$("#btnGetUserById").click(function () {
$('#userByName').empty();
$("#gettingByIdMsg").text(" Getting User...");
$.ajax({
url: '/api/User/getbyid/' + id: $("#userId").val(),
type: "GET",
success: function (data) {
$('<tr>', { html: formatItem(data) }).appendTo($('#userByName'));
$("#usersTable").removeClass("hidden");
$("#gettingByIdMsg").text("");
},
fail: function (jqXHR, textStatus) {
$("#gettingByIdMsg").text("Request failed: " + textStatus);
}
});
});

Using AJAX with MVC 5 and Umbraco

I need to use ajax in a partial view to call a function in a mvc controller to return a calculation.
FYI, I am using MVC 5 and Umbraco 7.
I currently have the ajax code within the partial view (will want to move this to a js file at some point).
Here is the ajax code:
function GetTime(name) {
var result = "";
$.ajax({
url: '/TimeDifference/GetTimeDifference',
//url: '#Url.Action("GetTimeDifference", "TimeDifference")',
type: 'GET',
//data: JSON.stringify({ location: name }),
data: ({ location: name }),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
cache: false,
success: function (msg) {
result = msg;
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
}
});
return result;
}
Here is the Controller:
public class TimeDifferenceController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpGet]
public JsonResult GetTimeDifference(string location)
{
DateTime utc = DateTime.UtcNow;
string timeZoneName = GetTimeZoneName(location);
TimeZoneInfo gmt = TimeZoneInfo.FindSystemTimeZoneById("GMT Standard Time");
TimeZoneInfo local = TimeZoneInfo.FindSystemTimeZoneById(timeZoneName);
TimeSpan utcOffset = gmt.GetUtcOffset(utc);
TimeSpan localOffset = local.GetUtcOffset(utc);
TimeSpan difference = localOffset - utcOffset;
return Json(Convert.ToInt16(difference.TotalMinutes),JsonRequestBehavior.AllowGet);
}
}
The above code gives me a 404 Not Found Error:
Request URL:http://localhost:100/TimeDifference/GetTimeDifference?location=BVI&_=1511949514552
Request Method:GET
Status Code:404 Not Found
Remote Address:[::1]:100
If I use:
url: '#Url.Action("GetTimeDifference", "TimeDifference")'
The #Url.Action("GetTimeDifference", "TimeDifference") is Null so it doesn't go anywhere.
I have also tried:
#Html.Hidden("URLName", Url.Action("GetTimeDifference", "TimeDifference"))
...
url: $("#URLName").val()
Url is still Null.
I have added entries in to the Global.asax.cs for routing i.e.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "TimeDifference", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
This doesn't seem to do anything.
I have gone through a lot of the questions raised previously and amended as per suggestions but nothing seems to work.
As I am new to this I'm sure it something very simple I am missing.
Many thanks,
HH
Your controller won't be wired automatically, and I don't think the global.asax.cs file will work either. You can either register a custom route for your controller in an Umbraco Startup Handler: https://our.umbraco.org/documentation/reference/routing/custom-routes or you can create your controller as an Umbraco WebApi Controller, which is designed for stuff like this: https://our.umbraco.org/documentation/Reference/Routing/WebApi/.
Umbraco WebAPI controllers get wired in automatically and will return either JSON or XML automatically depending on what the calling client asks for.

Invoking Action in Controller using ajax - not working. (ASP.Net MVC)

I've been wrestling this error for quiet a while now and tried all the suggestions found on the web, still no luck.
I'm doing a simple ajax call to a controller's action. The application is in EPiServer, but this seems to be a generic question regarding using Ajax in ASP.NET.
Index View:
<input id="btnAjax" type="button" value="Favorite" />
<script>
$('#btnAjax').click(function () {
$.ajax({
url: '#Url.Action("SetCookie", "Home")',
contentType: 'application/html; charset=utf-8',
type: 'POST',
dataType: 'html'
})
.success(function (result) {
alert("Success");
})
.error(function (xhr, status) {
alert(status);
})
});
</script>
Controller - HomeController:
[HttpPost]
public void SetCookie()
{
//Do stuff
}
What I've done/tried:
Referenced jquery correctly.
Added the [WebMethod] attribute to the action
Added a Http module in Web.config (ScriptModule, for EPiServer)
Added Reference to jquery.unobtrusive-ajax.js, after the reference to jquery.
When I run the webapplication and push the button the debugger in Developer tool tells me
which is strange, since there is an action/method called SetCookie() in the HomeController. And the alert box "Fail" shows, which indicated that at least the js function is invoked.
Either I'm blind and missing something or there is something else which needs to be done...
All suggestions are welcome and much appreciated.
/ChrisRun
EPiServer does not register the default route for MVC by default. This is because you could have a page called "Home" in your site that would confict with the Home route. You can register the route yourself in Global.asax by overriding the RegisterRoutes method:
protected override void RegisterRoutes(RouteCollection routes)
{
base.RegisterRoutes(routes);
// Register a route for Web API
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "webapi/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Register a route for classic MVC to use for API calls
routes.MapRoute(
name: "API",
url: "api/{controller}/{action}/{id}",
defaults: new { action = "Index", id = UrlParameter.Optional });
}
I like to put MVC and Web API routes under a prefix such as "webapi" or "api" so that it's less likely to conflict with any content routing.
Simply change your method from this:
public void SetCookie()
{
//Do stuff
}
to this:
public ActionResult SetCookie()
{
//Do stuff
}

Call web API string parameter

I have this function
[System.Web.Http.HttpGet]
[System.Web.Http.ActionName("StartProcess")]
public object StartProcess(string items)
{
//do stuff
}
trying to call with
$.ajax({
url: '/api/Details/StartProcess',
type: 'get',
contentType: 'application/json',
data: items,
success: function() {
logger.log('Successful', "", "", true);
},
error: function(error) {
var jsonValue = jQuery.parseJSON(error.responseText);
});
Keep getting 404 error. The rest of my calls work but this is the first one that I need to send a parameter.
items is just a comma delimited string.
this is my route info.
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id=Urlameter.Optional }
);
Any ideas what I am missing?
you are getting 404 error because your routing table is not able to resolve the url "/api/Details/StartProcess"
In order to make the WebAPI routing work you need to modify the "MapHttpRoute()" function of route collection and not the "MapRoute()"
So please change the API routing as below (assuming you are using default api) and it should work fine.
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { action = RouteParameter.Optional, id = RouteParameter.Optional }
);
The parameter in Web API needs to follow the parameter in routing config.
In your example the easiest would be to change string items to string id.
Alternatly you could add api/{controller}/{action}/{items} to the route config.
Also, if you don't fancy changing your API route config (which would lead to minor complications with calling simple Get and Put methods) you can change your controller action annotation from
[System.Web.Http.ActionName("StartProcess")]
to
[Route("StartProcess/{items}")]
Also, you'll need to annotate your controller with:
[RoutePrefix("api/details")]

Ajax Post: 405 Method Not Allowed

Within my API Controller called Payment, I have the following method:
[HttpPost]
public HttpResponseMessage Charge(Payment payment)
{
var processedPayment = _paymentProcessor.Charge(payment);
var response = Request.CreateResponse(processedPayment.Status != "PAID" ? HttpStatusCode.ExpectationFailed : HttpStatusCode.OK, processedPayment);
return response;
}
In my HTML page I have:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "http://localhost:65396/api/payment/charge",
data: $('#addPayment').serialize(),
dataType: "json",
success: function (data) {
alert(data);
}
});
Whenever I fire the POST, I get
"NetworkError: 405 Method Not Allowed - http://localhost:65396/api/payment/charge"
What am I missing?
Thank you.
UPDATE
Here's the routing information (default)
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Most likely your routing is not configured for the action to be invoked. Hence the request ends up in nowhere and ASP.NET Web API sends a blank-out message "method not allowed".
Can you please update the question with your routing?
UPDATE
As I thought! You are sending to http://localhost:65396/api/payment/charge while you need to send to http://localhost:65396/api/payment - assuming your controller is called PaymentController.
Note that route does not have action.
Turns out I needed to implement CORS support. http://blogs.msdn.com/b/carlosfigueira/archive/2012/02/20/implementing-cors-support-in-asp-net-web-apis.aspx
I had the same problem with my controller.
The only thing which is different is the ending of the URL.
Add "/" to "http://localhost:65396/api/payment/charge" at the end, that helped me

Resources