I'm just trying to test a very simple ajax call to a simple webservice. I'm using .net 4, iis 6. My webservice code looks like this...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
namespace ABCNamespace {
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class MyService : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string HelloWorld()
{
return new JavaScriptSerializer().Serialize("Hello World");
}
}
}
My call looks like this
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "../../MyService.asmx/HelloWord",
data: "{}",
dataType: "json",
success: function () { alert('done'); },
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
I'm keep getting 500 error and after taking a closer look, I'm getting a string back instead of json data. I think if correct this, it will fix my issue. However, I can't get it to return json data.
Here is a response check by invoking my webmethod
<?xml version="1.0" encoding="UTF-8"?>
<string xmlns="http://tempuri.org/"> "Hello World" </string>
Note: please ignore the fact that I'm using ../../ in my url instead of resolveURL. This is just for quick simple testing purposes. I also play around with the web.config handlers and no luck. Not sure what I miss...
Related
I am attempting to connect to a SOAP web service that implements its WS security by means of a SOAP header element using the Loopback SOAP connector.
Unfortunately, documentation regarding how to configure the soap header option of the connector is sparse.
It would be greatly appreciated if you could assist by indicating how the soap header should be constructed in order for the web service to authenticate successfully.
var loopback = require('loopback');
var path = require('path');
var app = module.exports = loopback();
app.set('restApiRoot', '/api');
var myHeader = {
Security:
{
UsernameToken:{
Username: "Staging Integration Store 3",
Password: "WSAUFbw6"
}
}
};
var ds = loopback.createDataSource('soap',
{
connector: require('../index'),
/* security: {
scheme: 'wsse',
created: null,
username: "Staging Integration Store 3",
password: "WSAUFbw6",
passwordType: 'PasswordText'
}, */
soapHeaders: [{
element: myHeader, // The XML element in JSON object format
prefix: 'wsse', // The XML namespace prefix for the header
namespace: 'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd' // The XML namespace URI for the header
}],
remotingEnabled: true,
// wsdl: 'https://staging.payu.co.za/service/PayUAPI?wsdl' // The url to WSDL
wsdl: path.join(__dirname, './PayUAPI.wsdl')
});
// Unfortunately, the methods from the connector are mixed in asynchronously
// This is a hack to wait for the methods to be injected
ds.once('connected', function () {
// Create the model
// var WeatherService = ds.createModel('WeatherService', {});
var RedirectPaymentService = ds.createModel('RedirectPaymentService', {});
// Refine the methods
RedirectPaymentService.payments = function (api,safekey,transactiontype,additionalInfo,customer,basket,cb) {
RedirectPaymentService.setTransaction({Api: api,Safekey: safekey,TransactionType: transactiontype,AdditionalInformation: additionalInfo,Customer: customer,Basket: basket}, function (err, response) {
console.log('SetTransaction: %j', response);
var result = (!err && response.return.successful.localCompare("true") == 0) ?
response.return.payuReference : response.return.resultMessage;
cb(err, result);
});
};
Response:
SetTransaction: {"statusCode":500,"body":"<soap:Envelope xmlns:soap=\"http://sch
emas.xmlsoap.org/soap/envelope/\"><soap:Body><soap:Fault><faultcode xmlns:ns1=\"
http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xs
d\">ns1:InvalidSecurityToken</faultcode><faultstring>An invalid security token w
as provided (An error happened processing a Username Token)</faultstring></soap:
Fault></soap:Body></soap:Envelope>","headers":{"date":"Tue, 17 Nov 2015 12:15:17
GMT","server":"Apache/2.4.12 (Win64) OpenSSL/1.0.2a mod_jk/1.2.40","x-distribut
ed-by":"AHC","content-length":"388","connection":"close","content-type":"text/xm
l;charset=UTF-8"},"request":{"uri":{"protocol":"https:","slashes":true,"auth":nu
ll,"host":"staging.payu.co.za","port":443,"hostname":"staging.payu.co.za","hash"
:null,"search":null,"query":null,"pathname":"/service/PayUAPI","path":"/service/
PayUAPI","href":"https://staging.payu.co.za/service/PayUAPI"},"method":"POST","h
eaders":{"User-Agent":"loopback-connector-soap/2.3.0","Accept":"text/html,applic
ation/xhtml+xml,application/xml,text/xml;q=0.9,*/*;q=0.8","Accept-Encoding":"non
e","Accept-Charset":"utf-8","Connection":"close","Host":"staging.payu.co.za","Co
ntent-Length":1128,"Content-Type":"text/xml; charset=utf-8","SOAPAction":"\"\""}
}}
events.js:141
Thanks
Setting the security in datasources.json works, but you probably don't want to save username and password there.
There a couple of options:
1) You could use add a vairable which can be pulled from config.json and embed into datasources.json
like so: "security": ${security}.
And variable security is defined in config.env.json.
2) In a model, eg if you have a Product model, then you could use something like:
Product.datasources.settings.security = {'scheme':'WS', 'username':'abc'....}
I managed to resolve this by making use of the the connector's security option which creates the relevant SOAP Security header, provided that the relevant data is supplied.
security: {
scheme: 'WS',
username: "Staging Integration Store 3",
password: "WSAUFbw6",
passwordType: 'PasswordText'
},
XML conversion
<soap:Header>
<wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<wsu:Timestamp wsu:Id="Timestamp-2015-11-20T08:00:46Z">
<wsu:Created>2015-11-20T08:00:46Z</wsu:Created>
<wsu:Expires>2015-11-20T08:10:46Z</wsu:Expires>
</wsu:Timestamp>
<wsse:UsernameToken xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="SecurityToken-2015-11-20T08:00:46Z">
<wsse:Username>Staging Integration Store 3</wsse:Username>
<wsse:Password>WSAUFbw6</wsse:Password>
<wsu:Created>2015-11-20T08:00:46Z</wsu:Created>
</wsse:UsernameToken>
</wsse:Security>
I have created a Datasnap REST server.
A ReverseString method gets created by default that simply reverses the string passed to the method.
When I invoke the method using the browser URL:
http://dummydomain.com:81/datasnap/rest/TServerMethods1/ReverseString/ABC
I receive {"result":["CBA"]} as result. (server runs on port 81 and the parameter passed to the method is ABC)
I have tried the following code to get the result into a variable in javascript, but without success:
var options={
type: "GET",
url: "http://dummydomain.com:81/datasnap/rest/TServerMethods1/SayHello",
data: "ABC",
dataType: "json",
success: function(data) {
var json = JSON.stringify(data);
$("p").after('<div id="data1">Your result is: ' + json.result + '</div>');
}
}
$.ajax(options);
What am I doing wrong? In the end I need 'CBA' in a variable. If there are some good resources out there, please advise. I have been googling but everybody seem to do it in their own way.
I am trying to call ASP.net 1.1 service in asp.net using Jquery, can't figure put what I am doing wrong here, Pleaseeeee help
Javascript Method
function YesCheckChanged(vSRID) {
var para = {
SRID: vSRID
};
jQuery.ajax({
type: "POST",
url: serviceUrl + "/YesRdoClicked",
dataType: "xml",
data: para,
contentType: "application/xml; charset=utf-8",
success: function(data, status) {
alert(data);
edata = $(data).find("string").text();
alert(edata);
},
error: function(e, status) {
alert(status);
}
});
}
Error
System.InvalidOperationException: Request format is invalid:
application/xml; charset=utf-8.
at System.Web.Services.Protocols.HttpServerProtocol.ReadParameters()
at System.Web.Services.Protocols.WebServiceHandler.CoreProcessRequest()
Service method Code
[WebMethod(true)]
public string YesRdoClicked(int SRID)
{
clsEntity obj = new clsEntity();
obj.New_DeleteTempEntity(SRID);
return "yes";
}
http://www.codeproject.com/Articles/1231/ASP-NET-Web-Service
I finally resorted to native Activex calls as no other way seem to work for me. Personally I wanted to avoid using it. But It works well.
A word of caution here, activeX are not very well supported in browsers other than IE so you need to either have IE Only application or convince the client to upgrade to higher version of asp.net.
i have a webservice whih has only one method in it
[WebMethod]
public string GetMovies()
{
using (var dataContext = new MovieCollectionDataContext())
{
var query = dataContext.Movies.Select(m =>new{m.Title,m.ReleaseDate}).Take(20);
var serializer = new JavaScriptSerializer();
return serializer.Serialize(query);
}
}
it serilize the object but when i get the result in firebug it look like this
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">[{"Title":"SQL","ReleaseDate":"\/Date(1224007200000)\/"},{"Title":"Termonator Salvation","ReleaseDate":"\/Date(1224007200000)\/"}]</string>
iam using Kendo and my jquery method is
var dataSource = new kendo.data.DataSource(
{
transport: {
read: {
type: "POST",
dataType: "json",
url: "/MovieService.asmx/GetMovies"
//contentType: "application/json; charset=utf-8",
}
},
change: function (e) {
alert(e);
},
error: function (e) {
alert(e[2]);
},
pageSize: 10,
schema: {
data: "d"
}
in the above jquery there is an error even when it calls i got this error
SyntaxError: JSON.parse: unexpected character
please help me to get the proper JSON plz i really neeed proper JSON to do my work
What exactly are you trying to parse? The whole response won't parse because it's XML, not json. If you are trying to parse just the value of the string element then you probably need to wrap it in quotes.
Update:
JSON.parse('[{"Title":"SQL","ReleaseDate":"\/Date(1224007200000)\/"},{"Title":"Termonator Salvation","ReleaseDate":"\/Date(1224007200000)\/"}]')
This blog post shows how to return JSON from an ASMX service: http://encosia.com/using-jquery-to-consume-aspnet-json-web-services/
And here is a running project showing how to bind a Kendo Grid to an ASMX service: https://github.com/telerik/kendo-examples-asp-net/tree/master/grid-web-service-crud
I attempt to use webservice return POCO class generated from entity data model as JSON when using Jquery AJAX call method in webservice. but I have problem with error "Only Web services with a [ScriptService] attribute on the class definition can be called from script", and getting stuck in it,
Here is my code :
namespace CarCareCenter.Web.Admin.Services
{
/// <summary>
/// Summary description for About
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class About : System.Web.Services.WebService
{
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod]
public static Entities.Category getAbout()
{
Entities.Category about = new Entities.Category();
using (var context = new CarCareCenterDataEntities())
{
about = (from c in context.Categories where c.Type == "About" select c).SingleOrDefault();
}
return about;
}
}
}
aspx page :
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
url: '/Services/About.asmx/getAbout',
data: '{}',
success: function (response) {
var aboutContent = response.d;
alert(aboutContent);
$('#title-en').val(aboutContent.Name);
$('#title-vn').val(aboutContent.NameVn);
$('#content-en').val(aboutContent.Description);
$('#content-vn').val(aboutContent.DescriptionVn);
$('#id').val(aboutContent.CategoryId);
},
failure: function (message) {
alert(message);
},
error: function (result) {
alert(result);
}
});
$('#SaveChange').bind('click', function () { updateAbout(); return false; });
$('#Reset').bind('click', function () { getAbout(); return false; })
});
function updateAbout() {
var abt = {
"CategoryId": $('#id').val(),
"Name": $('#title-en').val(),
"NameVn": $('#title-vn').val(),
"Description": $('#content-en').val(),
"DescriptionVn": $('#content-vn').val()
};
$.ajax({
type: "POST",
url: "AboutManagement.aspx/updateAbout",
data: JSON.stringify(abt),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var aboutContent = response.d;
$('#title-en').val(aboutContent.Name);
$('#title-vn').val(aboutContent.NameVn);
$('#content-en').val(aboutContent.Description);
$('#content-vn').val(aboutContent.DescriptionVn);
},
failure: function (message) {
alert(message);
},
error: function (result) {
alert(result);
}
});
}
</script>
Do any approaches to solve it ? Please help me . Thanks
just add Attribute Class [ScriptService]
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
old question. i had same problem, just removed contenttype from ajax call and it worked.
I just had exactly this same error message: "Only Web services with a [ScriptService] attribute on the class definition can be called from script.", but it had a totally different cause and solution.
It was working on my development machine, but not in production.
In my web.config I had:
<system.web>
<httpHandlers>
<remove verb="*" path="*.asmx"></remove>
<add verb="*" path="*.asmx" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral,PublicKeyToken=31bf3856ad364e35"></add>
</httpHandlers>
</system.web>
Replaced the Add tag with a newer assembly version:
<add verb="*" path="*.asmx" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
And it worked! Aparently the older assembly (1.0.61025.0) did not reccognise the attribute that was compiled against the newer (3.5.0.0) one.
Hope I can save someone the hours I needed to get to the bottom of this one!
I was also facing the same issue.
I just commented below code and it started working:
[System.Web.Script.Services.ScriptService]
available in .asmx file .
Just adding this in case someone else made the same stupid mistake I did.
Solution: Right click on the .asmx file in Visual Studio's Solution Explorer and select "View Markup". Verify that the value for the Class attribute is correct and not pointing to the wrong class. For some reason, the mismatch of the CodeBehind file and the Class name will throw this error instead of something more relevant.
Back story: Working on legacy code and wanted to use an .asmx web service to remain consistent with the rest of the code base. In VS2017, I couldn't find where to add that file so I just copied another .asmx file and renamed it. I should have known better. The issue is slightly masked because you are taken directly to the code behind file when you double click on the .asmx in the solution explorer, so it's easy to overlook that renaming the file does not update the Class attribute.