asp.net web api methods are not getting executed - asp.net-web-api

I am creating a web application in asp.net mvc with jQuery, I created a mvc application and included one web api controller, now my controller looks like the below
public class DefaultController : ApiController
{
[HttpGet]
[Route("Default/test")]
public string test()
{
return "1";
}
}
url of the application
https://localhost:44308/Home/about
but when I execute the method of my api the following error is coming
This site can’t be reached
I tried this with ajax call also but still the same problem
$.ajax({
type: 'GET',
url: 'https://localhost:44308/Default/test',
async: false,
global: false,
contentType: "application/json",
success: function (returnedData) {
console.log(returnedData)
}
});
I don't understand what I did wrong here

Change the route attribute
[Route("~/Default/test")]
public string test()
{
return "1";
}

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.

Method not allowed while using ajax put request asp.net mvc

I have the following AJAX request:
$.ajax({
url: "/api/newrentals",
dataType: "json",
type: "PUT",
data: columnDate
}).done(function() {
toastr.success("Rentals succesfully recorded.");
}).fail(function() {
toastr.error("Something unexpected happened.");
});
And here's my CONTROLLER:
using System.Web.Http; //I used the correct reference
public class NewRentalsController : ApiController {
[HttpPut]
public void updateRentalReturnDate(string columnDate){
var date = columnDate;
}
}
When I hit some button, the ajax request is executed but it does not reach the controller. I get the following error :
"message": "The requested resource does not support http method 'PUT'."
I have read many answers but nothing helped me. For instance, I made sure that the paramater name in ajax and in the controller should be same. I also put the [HttpPut] annotation in the controller method. What exactly am I missing here?

The requested resource does not support http method 'GET' ASP MVC

I have a MVC api and are using controllers to access my data but I am using ajax and knockoutjs to call my method but I am getting the following error: The requested resource does not support http method 'GET'. I have tried using [HttpGET] at the top of my controller method but it still does not work. I am not sure how to solve this problem.
Knock ViewModel doing my api call:
vm = {
Data: ko.observable(),
Bound: 0,
Load: function () {
$.ajax({
type: "GET",
url: "../api/adusers",
contentType: "application/json;charset=utf-8",
success: function (result) {
vm.Data(ko.utils.unwrapObservable(ko.mapping.fromJS(result)));
if (!vm.Bound) {
ko.applyBindings(vm, document.getElementById("form1"));
$('#tableUsers').show();
vm.Bound = true;
}
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
})
}
}
API Controller:
public class ADUsersController : ApiController
{
[HttpGet]
public static List<Models.Users> GetADUsers()
{
return AD.GetUsers(System.Configuration.ConfigurationManager.AppSettings["NETBios"]
, System.Configuration.ConfigurationManager.AppSettings["Container"]
, System.Configuration.ConfigurationManager.AppSettings["ADServerUN"]
, System.Configuration.ConfigurationManager.AppSettings["ADServerPW"]);
}
}
You declared your controller action as static which is obviously not supported. Controller actions are instance methods. So make sure you declared your action as an instance method:
public class ADUsersController : ApiController
{
[HttpGet]
public List<Models.Users> GetADUsers()
{
return AD.GetUsers(
System.Configuration.ConfigurationManager.AppSettings["NETBios"],
System.Configuration.ConfigurationManager.AppSettings["Container"],
System.Configuration.ConfigurationManager.AppSettings["ADServerUN"],
System.Configuration.ConfigurationManager.AppSettings["ADServerPW"]
);
}
}

JSON WebMethod not working in Sitefinity

I am trying to call via ajax a WebMethod hosted in a traditional ASP.Net WebForm code-behind page. Here is the code for the WebMethod:
[WebMethod]
public static object States()
{
StateProvince[] states = new StateProvince[] { };
ApplicationServiceClient proxy = null;
try
{
proxy = new ApplicationServiceClient();
states = proxy.GetStateProvinces();
}
finally
{
CloseServiceProxy(proxy);
}
return states;
}
The WebMethod works just fine in my stand-alone development environment or if deployed normally to IIS, but when I deploy the aspx page to Sitefinity, I get the following exception when it's called:
Server Error in '/' Application.
Unknown web method States.aspx.
Parameter name: methodName
I'm not sure if Sitefinity is hijacking the URL and post-pending the ".aspx" or what is going on here.
Here is the jquery call that is calling the web method:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Regions.aspx/States",
data: "{}",
success: function(data) {
// implementation omitted
},
error: function(xhr, msg) {
alert(xhr.responseText);
}
});
I can replicate the problem by posting the request manually using Fiddler.
Again, this works just fine everywhere except when deployed to Sitefinity. Anybody have any thoughts?
What version of .NET is Sitefinity running? Page methods are a recent addition.
use dataType: "json",

Resources