Access Webservice from another Application - c#

I have an WebService in C# and I want to access this webservice from another application.
Ex. Have one webservice running in localhost and i also have a website running in localhost, and this two projects are in diferents places. The question is: How do I invoke this webservice from my website with ajax, both in localhost.
The Code that i have is this:
WebService
[System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public String HelloWorld()
{
return "Hello World";
}
}
and Client
$.ajax({
type: "POST",
url: "localhost:52137/Service1.asmx?op=HelloWorld",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: '',
success: function (data, status) {
alert(data.d);
},
error: function(data, status){
alert(status);
}
});

Try changing url to this:
url: "http: //localhost:52137/Service1.asmx/HelloWorld"
And BTW.. if the website is running on a different port than the service.. you still have xdomain issues.
CORS ASMX

As these two projects are in different places, it would be CORS request.
You need to enabled cross domain request in your service application as suggested in this article.
You can use $.getJSON which allow cross domain request.
As you're using C# you can create HTTP Handler as shown in this article.

Related

HTTP Error 405 When Using HTTP Delete Only on Host .Net Core 6

I'm getting a 405 error when trying to Delete from any Controllers. I can do it just fine in VS IDE, but cannot figure out why Not in host (request will sent by ajax)
Header Controller
[Authorize]
[Route("Api/v{version:apiVersion}/Cart")]
[ApiVersion("1.0")]
[ApiController]
public class CartApiController : ControllerBase
Note that: tried with CartApiController : Controller too
Controller
[HttpDelete("{CartId:long}", Name = "DeleteCart")]
public IActionResult DeleteCart(long CartId)
{
if (!_CartRepository.DeleteCart(CartId,Convert.ToInt64(_AccountRepository.GetClaim("ID"))))
return Ok(_ResultContentRepository.GetResultContent(1));
return Ok(_ResultContentRepository.GetResultContent(200));
}
Sender
SendApiAsync("Api/Cart/" + input.id, "delete", null, true, false, false).then(function () {
location.reload();
});
Part of Ajax
$.ajax({
url: Url,
headers: Headers,
type: Type,
async: true,
data: Data,
contentType: "application/json",
dataType: 'json',
success: function (data) {
etc...
}
note that:
this Api Sender Works fine by all Methods except http delete only on host
didn't wrote the complete code for Api sender
if url has a api address, url will be replace with the right path
(it's not a path problem)
I've Asked About this issue with the support team of my website Hosting and they told me it's a security configuration I can't use Http Delete so I Changed Every Http Delete to Http Get Starting With "Delete/" Path

Jquery Ajax call to ASMX web service error

I have a ASP.NET Web Forms application that has an ASMX web service file with a single method at the moment. I am trying to call that method from another file in the same project, but it does not seem to be working. When I look at my console window in chrome it states there is an internal 500 error with the web service. using the ASMX interface I am able to manually invoke the method, but it doesn't invoke from my AJAX code. I have been unable to determine the source of my error.
ASMX Web Method
[WebMethod]
public string TestMethod()
{
string x = "{Name:Shooter McGavin}";
return x;
}
JQuery from ASP.NET Page. I know the click event is firing and I also confirmed that the code is progressing inside the IF statement if the form is valid.
$("#AddSupplierBtn").click(function()
{
if ($("#AddSupplier").valid())
{
$.ajax({
type: "POST",
url: "/StockPileDelivery.asmx/TestMethod",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.data);
}
});
}
});

Consume ASP .Net WebService using HTML AJAX

I am trying to call a simple hellowworld function of ASP .NET WebService using JQuery AJAX call written in separate HTML file i.e. Not aspx file in ASP .NET.
Here is code of my AJAX call which works fine in aspx based web client.
$.ajax({
type: "POST",
url: "/Test1/RSSReader.asmx/GetRSSReader",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#output").text(msg.d);
},
error: function (e) {
$("#output").html("WebSerivce error " + e.responseText);
}
});
I want to call same webservice and same method using .html file but it is returning error. I tried giving server address i.e. localhost but still no response.

JQuery Cross Domain Error - No 'Access-Control-Allow-Origin'

The POST request
var url = "http://xxx.xxx.x.x/MyServices.svc/GetOrders";
$.ajax({
type: "POST",
url: url,
crossDomain : true,
data: 'abcd',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
data = result.data;
},
error: function (xhr, ajaxOptions, thrownError) {
debugger;
alert('error');
}
});
When the url address is localhost i am getting a response
When trying to do so across servers I am getting an Error:
405 (Method Not Allowed)
XMLHttpRequest cannot load http://xxx.xxx.x.x/MyServices.svc/GetOrders. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
All of the answers on the web where inconclusive.
If you can deal with json in return, then try using jsonp for speaking between domains:
$.ajax({
type: "POST",
dataType: 'jsonp',
...... etc ....
As documented in official site :-
The advent of JSONP — essentially a consensual cross-site scripting
hack — has opened the door to powerful mashups of content. Many
prominent sites provide JSONP services, allowing you access to their
content via a predefined API.
and
jQuery handles all the complex aspects of JSONP behind-the-scenes —
all we have to do is tell jQuery the name of the JSONP callback
parameter specified by YQL ("callback" in this case), and otherwise
the whole process looks and feels like a normal Ajax request.

WCF "Method Not Allowed" in Visual Studio integrated webserver

I have two web projects in Visual Studio 2008 SP1, One hosting a WCF service and another that I am using to consume the WCF service. The service in question exposes a webHttpBinding endpoint and take JSON as input and returns JSON.
I have used Jquery ajax to consume the service from the client web app like so:
$(document).ready(function () {
var data = '{"myobject":{"Business":"PIZZA"}}';
$.ajax({
type: "POST",
contentType: "application/json",
data: data,
dataType: 'json',
url: "http://localhost:1212/JobInfo.svc/ReturnThisString",
error:
function(XMLHttpRequest, textStatus, errorThrown) {
alert("Error");
},
success: function(data) {
alert("BoolValue: " + data.GetDataUsingDataContractResult.BoolValue);
alert("StringValue: " + data.GetDataUsingDataContractResult.StringValue);
}
});
});
And I get the following error in the Firebug HTML request:
http://localhost:1212/JobInfo.svc/ReturnThisString 405 Method Not Allowed
But if run the exact same file in the web project that is hosting the project it works fine.
The hosting project is running on set port localhost:1212 and the client on localhost:RANDOM_PORT. As the localhost is the same I would imagine its not a Cross Domain issue? Or does the port part count also?
The server contract is as follows:
[OperationContract]
[WebInvoke(Method="POST",UriTemplate="ReturnThisString",
BodyStyle=WebMessageBodyStyle.Wrapped,
RequestFormat=WebMessageFormat.Json,
ResponseFormat=WebMessageFormat.Json)]
EventListArgs ReturnThisString(EventListArgs myobject);
[Serializable]
[DataContract]
public class EventListArgs {
[DataMember( IsRequired = false)]
public string Business;
[DataMember( IsRequired = false)]
public string Feeder;
}
And the implemented code is:
public EventListArgs ReturnThisString(EventListArgs myobject)
{
return myobject;
}
This was added as a simple method to prove I had not just done something silly. What I like to call a sanity check. Its a simple function that takes a complex(of type other then string) JSON object as a parameter and returns a complex JSON object.
As you can see above I have two web project that use the Visual Studio Built in web server (local IIS install not possible). The above configuration does not work but if you can see I have also got the Darkside test page in the server host which is an exact copy from the client and this work with no problems at all.
Try using IIS Express
It's got the same features as a full blown IIS and requires no install.
A simple command line is all you need to start it up. It should get rid of the Casini related errors you were getting.

Categories