XMLHttpRequest cannot load URL. Invalid HTTP status code 400 - javascript

I have WebApi Application and one MVC5 Applicatiion.I am sending request to webApi using angularJS from MVC5 Application.But it is not working fine when I send DELETE or POST request. I am getting 'XMLHttpRequest cannot load URL. Invalid HTTP status code 400' error in Browser.But it is working fine for GET request.See the below code.
Sevice call
$http.delete("http://localhost:8643/api/values/1");
WebApi
// DELETE api/values/5
[HttpDelete]
public void Delete(int id)
{
var emp = employees.FirstOrDefault(x => x.ID == id);
if(emp!=null)
{
employees.Remove(emp);
}
}
Even I have enabled Cors in my WebApi.
Can anyone please help me.

For the post try to add $.param to your object, and specify the content type.
Something like that.
$http({
method: "POST",
url: "http://localhost:8643/api/values",
data: $.param({'Type': 'Type', 'Name': 'Name'}),
headers: {'Content-Type': 'application/x-www-form-urlencoded',}
})
Hope this might help.
As for Delete and Put, I am still having problems with them myself.

Related

Ionic: My http.post to WebApi RestFull doesn't work

I'm developing an app with Ionic Framework and I'm changing some of the information with my web service API RestFull. When I connect with a GET method it works, but when I try to connect with a POST method it doesn't work.
This is the code of Ionic:
import { HttpClient ] from '#angular/common/http';
constructor(private http: HttpClient ...)
And this is the function (I am returning a promise):
var user = {"nom" : "whatever", "password" : "whatever2"};
var options = { headers: {'Content-Type': 'application/json; charset=utf-8;'}};
return this.http.post(myLink, user, options).toPromise();
In Web Service, the code is (C#):
[Route("AuthFullUser")]
[HttpPost]
public HttpResponseMessage login([FromBody]User user){
var u = UserRepository.login(user.nom.ToString(), user.password.ToString());
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, u);
return response;
}
If I try to enter from Ionic doesn't work, but with PostMan (an app) it works.
On the other hand, if I put [HttpOptions] above the [Route("AuthFullUser")] I am able to access the web service but the parameters are NULL.
I tried to make a request with $.ajax{} or $.post{} but neither worked.
I tried to add on my headers:
"Acces-Control-Allow-Origin" : "*",
"Acces-Control-Allow-Credentials" : "true",
"Acces-Control-Allow-Methods" : "GET, POST, PUT, DELETE, OPTIONS",
"Acces-Control-Allow-Headers" : "Content-Type"
But neither worked.
I have been struggling for weeks on this. Any help would be greatly appreciated.
If someone is having the same trouble I found the solution.
It was all from the Web Service and his headers.
You only need to allow all the headers, it's all on the documentation.
If someone have a question, they can put it here and i will try to give my best answer.

Angular http GET 405 (Method Not Allowed)

I'm implementing another function in an application (made with angular), I call an API (made with Lumen) and it returns a 405 error whem i tried in local and "XMLHttpRequest cannot load Response for preflight is invalid (redirect)" when i tried on the server. I read about CORS but it's already implemented, I think if it isn't none of others functions would work.
Another thing, if I make the call with Advanced Rest Client it works fine :(
sorry about my english, i don't speak it so much.
function on application
$scope.agencias = [];
$http({
method: 'GET',
//url: 'http://api-beta.grupoaldorf.com.mx/agencias/',
url: 'http://localhost:8000/agencias/',
headers: agenciaMazda.headers
}).then(function successCallback(response) {
$scope.agencias = response.data;
console.log("regreso del http");
console.log($scope.agencias);
}, function errorCallback(response) {
//callback(false);
});
route on web.php
$app->get('agencias','CitasController#agenciasDisponibles');
controller in CitasController.php
public function agenciasDisponibles(Agencia $agencia){
$fabricante = $this->request->header('Aldorf-App');
$disponibles = Agencia::where('fabricante', $fabricante)->where('mostrar', 1)->select(['codigo', 'nombre'])->get();
return $disponibles;
}
Finally i solved it, it was really dumb, i added a slash at the end of the uri xD it had to be "http://localhost:8000/agencias" instead of "http://localhost:8000/agencias/"

C# [WebMethod] is not hitting when Content-Type ''application/Json" is not provided

I have created a C# WebMethod
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static HttpResponseMessage GetPageHtml(string file, int page)
{}
I am able to call it and it works fine using Ajax, angular, Postman when i add header Content-Type : 'application/Json'. Here is the sample HTTP request which is working fine.
$http({
url: 'default.aspx/GetPageHtml?file=' + JSON.stringify(selectedFile) + '&page=' + itemNumber,
method: "GET",
headers: { 'Content-Type': 'application/json' },
data:''
}).then(function successCallback(response) {
return response.d;
}, function errorCallback(response) {
});
But when i call the same method as a for iframe ng-src it is not working.
<iframe ng-src="default.aspx/GetPageHtml?file=candy.pdf&page=1" style="height: 150px;"></iframe>
I inspected this Http call over Google Chrome's Developers tools and found that Content-Type is 'text/html' there, that is why it is not hitting my WebMethod. Please see this screenshot.
Iframe ng-src
I investigated a lot over Google and Stackoverflow, but i could not find a reason why i need to provide Content-Type : 'application/json' to call my WebMethod
I further investigated my question and tried to find other ways around, I came up with a solution. I created a new WebForm named GetDocumentHtml.aspx and in its Page_Load Method i am doing operation which i was previously doing in GetPageHtml WebMethod.
Now in iframe ng-src i am providing this URL
/GetDocumentHtml.aspx?file=calibre.docx&page=1
Instead of
default.aspx/GetPageHtml?file=candy.pdf&page=1
In Page_Load Method i am using following code to get URL parameters
var file = GetValueFromQueryString("file");
var page =Convert.ToInt32(GetValueFromQueryString("page"));
GetValueFromQueryString Method
private String GetValueFromQueryString(String value)
{
try
{
return Request.QueryString[value].ToString();
}
catch (System.Exception exp)
{
return String.Empty;
}
}
I hope this information will be helpful for someone. Thanks.

How can I test my web api Post Web method to know what's going on inside?

So here's my situation...
We have an on-prem installation of Microsoft Dynamics CRM and I am trying to make an ajax call from it to a service I created on another one of our servers. There have been many issues already that I've solved - but I'm able at this point to successfully make a GET request to my service from CRM via javascript I've put on a form in CRM.
Just for reference (because I'm not entirely sure at this point if these things are related or not)...
I had to set anonymous authentication in IIS for my service (CRM has
its own authentication that I will be relying on)
I had to set a response header of Access-Control-Allow-Origin with the host address of our CRM installation
So, after doing those things I was able to successfully call my web service via GET. I could return back a string I had from a [HttpGet] web method.
But, now I need to actually call a web method via POST to post some data to my web service. So, below you can see my implementation for the service as well as the javascript I'm using the make the POST call.
using CRMService.Models;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net.Mail;
using System.Web;
using System.Web.Http;
namespace CRMService.Controllers
{
public class DefaultController : ApiController
{
// GET: Default
public string Get()
{
return "Hi";
}
[HttpPost]
public string GiveParameters(TestClass tc)
{
try
{
Dictionary<string, object> Parameters = new Dictionary<string, object>();
Parameters.Add("id", tc.id);
Parameters.Add("one", tc.one);
Parameters.Add("two", tc.two);
NonQuery("InsertTestItem", ConfigurationManager.ConnectionStrings["TestConnection"].ToString(), Parameters);
return "success";
}
catch (Exception ex)
{
return "ex";
}
}
}
}
var new_budget = Xrm.Page.data.entity.attributes.get("new_budget").getValue();
var new_name = Xrm.Page.data.entity.attributes.get("new_name").getValue();
var id = Xrm.Page.data.entity.getId();
data = '{"TestClass":{"one":"' + new_name + '", "two":"'+ new_budget +'", "id":"'+ id +'"}}'
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "https://<hiddingMyUrl>/api/Default/GiveParameters",
data: data,
dataType: "json",
success: function(data) {
console.log("Success");
},
error: function(result) {
console.log("Error");
}
});
When I make this POST call, at first I could see it was doing some "preflight" stuff and making an OPTIONS request - then returning a 403 (I think, if memory serves me right). I looked that up and solved that issue by adding a Access-Control-Allow-Headers header to my web service in IIS with the value of Origin, X-Requested-With, Content-Type, Accept
After doing that my POST actually gives a 200 status code - but, as you can see in my code, I should then be seeing data in a database if everything went well.
..So of course then the question is... is my web service code working properly? And normally I could test for that easily - however I am fairly new to web api. I don't really get the best way to testing at this point - and I don't know if it's something with my code specifically or if there is some configuration issue with web api itself.
Here is my routeconfig:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { action = "Index", id = UrlParameter.Optional }
);
}
You should try working with a REST client.
Here are two nice ones :
Advanced Rest Client
Postman
I personally prefer Postman but really both are good.

Web API: Method Not Found and Method Not Allowed

I can't seem to make an ajax call to my Web API controller. Either the URL isn't right (method not found) or I get a method not allowed error. This is my ajax call:
$.ajax({
url: 'server/InstallApp',
type: 'POST',
data: {server: serverAsJson, appWithGroup: appWithGroupAsJson},
contentType: "application/json",
success: InstallRequested
});
That ajax call is being called from this URL:
http://serverName/PrestoWebApi/app/#/server/ApplicationServers%5E%5E8
These are the various URLs I've tried to use in the above ajax call, and the result:
url: 'server/InstallApp'
POST http://serverName/PrestoWebApi/app/server/InstallApp 404 (Not Found)
Notice that the # is missing. Not sure if that matters.
url: '#/server/InstallApp'
POST http://serverName/PrestoWebApi/app/ 405 (Method Not Allowed)
Not sure why the URL is truncated like that. Why Method Not Allowed when the URL doesn't even match the controller?
url: '/PrestoWebApi/app/#/server/InstallApp'
POST http://serverName/PrestoWebApi/app/ 405 (Method Not Allowed)
I'm not sure what to try. I've done this with other apps. I even tried putting webdav removal entries in my web.config.
This is my controller (note that I can call the Get method in my controller):
[EnableCors(origins: "http://serverName", headers: "*", methods: "*")]
public class ServerController : ApiController
{
public ApplicationServer Get(string id)
{
// Get code here
}
[HttpPost]
public void InstallApp(ApplicationServer server, ApplicationWithOverrideVariableGroup appWithGroup)
{
Debug.WriteLine("snuh");
}
I'm at a loss. Any ideas on what to try?
The # in your URL is used for client side logic, most likely routing, and is completely ignored in your WebAPI routes.
i.e. this URL:
http://serverName/PrestoWebApi/app/#/server/ApplicationServers%5E%5E8
Is interpreted as this on the server:
http://serverName/PrestoWebApi/app/
The second issue I see is that, unless you specifically changed this in your WebApiConfig, your WebAPI methods do not reside at /app, rather /api (or possibly /server in your case). You could change your ajax call to:
$.ajax({
url: '/PrestoWebApi/server/InstallApp', // or /PrestoWebApi/api/server/InstallApp
type: 'POST',
data: {server: serverAsJson, appWithGroup: appWithGroupAsJson},
contentType: "application/json",
success: InstallRequested
});
You can see exactly what the URL should look like by going to the WebAPI welcome page (probably http://serverName/PrestoWebApi/api) and looking at the Help page by clicking Api from the navigation bar.
The URL for your ajax call should be, "HTTP://{{domainname}}.com/api/{{controller}}"
For example, "http://myapiproject.com/api/server"... unless you have your controller in a different directory than "Controllers."
Then, since you've set the HttpPost attribute on the "InstallApp" method of your controller, you just make sure that the 'type' setting in your ajax call is set to 'POST' and it should route.
Doing it this way, you won't be able to have two methods with the [HttpPost] attribute added to it.

Categories

Resources