Asp.Net web-api ajax call 404 method not found - asp.net

I am using Asp.net mvc4 web-api.
I got an error 404 method not found, i am calling DelteMenu Method using jquery ajax. I am pssing argument Using data : of Jquery ajax. if i am passing Model parameter it is working fine but for other parameters like Guid, String throwing exception : 404 method nod found.please let me know if you have any idea why it is throwing 404 error.
//api method
public HttpResponseMessage DeleteMenu(Guid MenuId)
{
try
{
MenuDA.DeleteMenu(objMenuModel.MenuId);
return this.Request.CreateResponse(
HttpStatusCode.OK,
new
{
Success = true
});
}
catch (Exception ex)
{
ErrorLogDA.LogException(ex);
throw ex;
}
}
//Jquery ajax function
function performdeletemenu(MenuId)
{
if (confirm('Are you sure you want to delete this menu?'))
{
$.ajax({
type: 'DELETE',
url: '/api/MenuWebApi/DeleteMenu/',
data: "MenuId=" + MenuId,
success: function (data)
{
if (data.Success == true)
{
GetMenuList();
}
},
error: function (xhr, textStatus, errorThrown)
{
//window.location = JsErrorAction;
},
dataType: "json",
headers:
{
'RequestVerificationToken': JsTokenHeaderValue
}
});
}
return false;
}
Regards

The data setting does not work when sending a HTTP DELETE through jQuery's ajax function. You will have to pass the Guid in the url itself: url: '/api/MenuWebApi/DeleteMenu?MenuId=' + MenuId.
What I do find strange is that a 404 is returned, instead of a 400 Bad Request.

Add this line in RouteConfig.cs as below
routes.IgnoreRoute("{*x}", new { x = #".*\.asmx(/.*)?" });
I tool reference from https://stackoverflow.com/a/17058251/2318354
It will work definately in case of 404 Error Method not found.

Related

ajax call status is 200 but it is not successfull

I working on mvc asp.net project. I call my controller function with ajax, the call status is 200 but it is not successful, and goes to error section.
service:
public async Task<IEnumerable<TeamDto>> GetAllTeamsList()
{
var teams = await _teamRepository.GetAll().Include(u => u.Users).ThenInclude(m => m.User).ToListAsync();
return ObjectMapper.Map<IEnumerable<TeamDto>>(teams);
}
Controller:
public async Task<IEnumerable<TeamDto>> GetTeams()
{
var teams = await _teamAppService.GetAllTeamsList();
return teams;
}
js file:
$.ajax(
{
type: "GET",
url: "/App/Team/GetTeams",
success: function (data) {
///
},
error: function (data) { console.log("it went bad " + JSON.stringify(data)); }
});
Error:
TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
this is what I get when copy the url in the browser:
{"result":[{"tenantId":1,"name":"admin
team","users":[{"tenantId":1,"userId":2,"teamId":58,"user":{"profilePictureId":null,"shouldChangePasswordOnNextLogin":false,"signInTokenExpireTimeUtc":null,"signInToken":null,"googleAuthenticatorKey":null,"pin":"1234","hourlyRate":0.00,"payrollId":"","warehouseId":1,"tandaUser":null,"normalizedUserName":"ADMIN","normalizedEmailAddress":"ADMIN#DEFAULTTENANT.COM","concurrencyStamp":"bd7ee91e-587b-4ae2-bc97-be2ce7d7789b","tokens":null,"deleterUser":null,"creatorUser":null,"lastModifierUser":null,"authenticationSource":null,"userName":"admin","tenantId":1,"emailAddress":"admin#defaulttenant.com","name":"admin","surname":"admin","fullName":"admin
admin","password":"AQAAAAEAACcQAAAAENfcSE+zBppFKVxKUynGBiy4WZgDU3C3gbbWnQUdEyBb5J/S0uLkcqk+2MwM0DXxjw==","emailConfirmationCode":null,"passwordResetCode":null,"lockoutEndDateUtc":null,"accessFailedCount":1,"isLockoutEnabled":true,"phoneNumber":"","isPhoneNumberConfirmed":false,"securityStamp":"07a4d582-7233-3fbc-f3f7-39f015ee388b","isTwoFactorEnabled":false,"logins":null,"roles":null,"claims":null,"permissions":null,"settings":null,"isEmailConfirmed":true,"isActive":true,"isDeleted":false,"deleterUserId":null,"deletionTime":null,"lastModificationTime":"2020-09-30T02:54:34.402372Z","lastModifierUserId":null,"creationTime":"2019-09-05T23:27:47.8514365Z","creatorUserId":null,"id":2},"team":{"tenantId":1,"name":"admin
team","users":[
Open up the developer tools and look at the URL it is trying to request. Normally in the context of the application, you don't have the /App defined. In fact, you can use ASP.NET MVC Url helper to get the action method, to make sure the path is correct:
$.ajax({
type: "GET",
url: "#Url.Action("GetTeams", "Team")",
Also, normally you would return data via JSON from the controller like:
public async Task<IEnumerable<TeamDto>> GetTeams()
{
var teams = await _teamAppService.GetAllTeamsList();
return Json(teams, JsonRequestBehavior.AllowGet);
}
And maybe that would make a difference, using Json() from the asp.net mvc controller. Note AllowGet ensures that GET requests on an action returning JSON works, otherwise it will be blocked and return an error.

How to make an Ajax call to action method in different controller

I have following scenario.
Route Config:
routes.MapRoute(
name: "SellerRegistration",
url: "Registration/{action}/{id}",
defaults: new { controller = "SellerRegistration", action = "Seller", id = UrlParameter.Optional, area = "" },
namespaces: new[] { "MyCompany.Controllers" }
);
So when the url is www.example.com/Registration/Seller, the above route will match and displaying the view without any issues.
class SellerRegistration
{
public ActionResult Seller()
{
return View("Seller");
}
[AjaxOnly]
public bool ValidateUserEmail(string email)
{
return _userService.ValidateUserEmail(email);
}
}
Inside my view Seller.cshtml, I'm trying to make an ajax call to the method ValidateUserEmail().
I'm making ajax call as below:
$.ajax({
type: "POST",
url: rootUrl + "/SellerRegistration/ValidateUserEmail",
cache: false,
async: false,
data: { email: $("#Email").val() },
success: function (data) {
if (data === 'True') {
//redirect to login page
window.location.href = newUrl;
} else {
$("#otherDetails").show();
$("#emailValidation").hide();
$("#submitCompleteFormDiv").show();
}
},
error: function (data, jqXhr) {
console.log(jqXhr.status);
}
});
I have also tried generating url as below in the above ajax method.
url: '#Url.Action("SellerRegistration", "ValidateUserEmail")'
But I'm getting
401 - Unauthorised error.
I'm guessing that I'm not able to make ajax call because of the routing I configured. But, that routing is required to meet other scenarios in the application.
When ajax call is made, the url format is like www.example.com/Registration/Seller
So browser initiates an ajax call to the ValidateUserEmail method inside the controller SellerRegistration from www.example.com/Registration/Seller.
Because there is no real controller named Registration, when the ajax call is made to ValidateUserEmail() inside SellerRegistration controller, I'm getting 401 Unauthorized error.
Can someone please suggest if there is any technique or workaround to make it possible.
Thank you.

jquery ajax post with error and success message returned from the server

Here is my view
<div>
#using ( Html.BeginForm("jQueryPost", "Home",null, FormMethod.Post, new { id="FormPost" }))
{
#Html.TextBoxFor(x=> x.Name)<br />
#Html.TextBoxFor(x => x.LastName)<br />
#Html.TextBoxFor(x => x.Age)
<input type=submit value="submit" />
}
</div>
<script>
$(document).ready(function () {
$('#FormPost').submit(function (e) {
//This line will prevent the form from submitting
e.preventDefault();
alert('ajax post here');
$.ajax({
type: 'POST',
url: $('#FormPost').attr('action'),
data: $('#FormPost').serialize(),
accept: 'application/json',
error: function (xhr, status, error) {
alert('error: ' + xhr.statusText);
},
success: function (response) {
alert('resp: ' + response.data);
}
});
});
});
</script>
This is the Home controller's method the form posts to:
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult jQueryPost(IndexVM vm)
{
IndexVM _vm = vm;
return Json("name posted was: " + _vm.Name);
}
When I submit the form I get a 'resp: undefined' in the alert box. How do I return the text "name posted was: .... " back to the view on a successful post?
Also for exceptions when I added this line to the action
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult jQueryPost(IndexVM vm)
{
IndexVM _vm = vm;
throw new Exception("custom error string from action");
return Json("name posted was: " + _vm.Name);
}
I get the message 'error: Internal Server error'. I want to return the text of the message in the error like so: 'error: custom error string from action' what is the way to do that?
Thanks
Try changing you code like this,
error: function (xhr, status, error) {
alert('error: ' + xhr.statusTexterror);
},
success: function (response) {
alert('resp: ' + response);
}
Update
Following are the properties/ methods in xhr
readyState
status
statusText
responseXML and/or responseText when the underlying request responded with xml and/or text, respectively
setRequestHeader(name, value) which departs from the standard by replacing the old value with the new one rather than concatenating the new value to the old one
getAllResponseHeaders()
getResponseHeader()
statusCode()
abort()
If you just throw exceptions in controller actions like that, there isn't a friendly way to get them come back to the front-end. If you notice, you will end up with page html from the default template for exceptions.
On another note, I don't believe this is a good practice since you are just throwing them to get a message coming back.
A good way to handle "errors" from ASP.NET MVC controllers is explained in another question.
asp-net-mvc-ajax-error-handling

ASP.NET MVC 4 : enabling XmlHttpRequest post to controller with $.ajax()

Seems a simple thing but I've spent all day looking through posts all over the web with little recourse! Please help. I have a simple request to be posted to a MVC controller...
$(document).ready(function () {
$('#json_request').on("click", function () {
// send request to server for menu json data
$.ajax({
type: "POST",
url: location.protocol + "//" + location.host + "/Tablet/Menu",
data: { restaurantId: $('#restaurantId option:selected').val(), mealSessionId: $('#mealSessionId option:selected').val() },
success: function (menuData) {alert(menuData); },
error: function () { alert("failed"); }
});
});
});
The request just won't reach the controller! The app works fine when I post the request as a Html form. It works fine with the Visual Studio Development Server too.
I get 404 error with IIS 7.0 / ASP.NET / MVC 4. Possibly, contentType: application/x-www-form-urlencoded does not get through the http-protocol filters. Do I have to set those specifically? How? Thanks for your help. I am not send the request as a json, so i did not try contentType: application/json.
Controller / Action:
[HttpPost]
public ActionResult Menu(short restaurantId, short mealSessionId)
{
try
{
MenuInput menuInput = new MenuInput(restaurantId, mealSessionId);
menuInput.LoadMenu();
if (Request.IsAjaxRequest())
{
MemoryStream ms = new MemoryStream();
menuInput.AsJson(ms);
string jsonString = Encoding.UTF8.GetString(ms.ToArray());
JsonResult result = Json(jsonString, "text/x-json");
ms.Close();
return result;
}
else
{
return View("MenuInformation", menuInput);
}
}
catch (Exception ex)
{
System.Console.Write(ex.ToString());
return View();
}
}

XHR statusText not being set

What would cause the XHR to get overriden? I'm assuming that's what's happening here.
I am setting the status and code, show here, with a helper class:
if (program.Name == programName)
{
ServiceHelper.SetHttpError(501, "'Program Name' Already Exists.'");
return;
}
class:
public static void SetHttpError(int statusCode, string message)
{
HttpContext.Current.Response.StatusCode = statusCode;
HttpContext.Current.Response.StatusDescription = message;
}
handling the xhr:
function CallService(method, jsonParameters, successCallback, errorCallback)
{
if (errorCallback == undefined)
{
errorCallback = function(xhr) {
if (xhr.status == 501) {
alert(xhr.statusText);
}
else {
alert("Unexpected Error");
}
}
}
$.ajax({
type: "POST",
url: method,
data: jsonParameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successCallback,
error: errorCallback
});
}
At one time this was working.. now all that the alert shows is "error" not the message I'm providing..
Any idea?
What version of jQuery are you using? The latest docs say that the signature of the error callback is:
error(jqXHR, textStatus, errorThrown)
Your message might be in the textStatus argument.
Have you tried using FireBug to break on the error function and look at the properties of the xhr object?
I came just accross a similar issue where this statusText was not set, but only when using HTTPS on IIS, whereas it would work on on plain HTTP. I eventually found that IIS only supports HTTP2 on TLS, and in HTTP2 there is no status code description anymore.
When I used Fiddler to troubleshoot, it worked in both http and https, probably because of this !
In ASP.NET MVC you just can't use HttpStatusCode(code,description) anymore because the description will go nowhere. You have to pass the description e.g. into the response body instead. Or disable HTTP2 for the time being.

Resources