Remove xml header from C# webservice - c#

I need to build an API using C# webservice, which needs to return values in json format.
Currently I have the following lines of code
namespace WebService1
{
/// <summary>
/// Summary description for Service1
/// </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 Service1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return new JavaScriptSerializer().Serialize(new { errMsg = "test" });
}
}
}
The output of this when the post method is invoked is
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.org/">{"errMsg":"test"}</string>
But this isn't a valid json how do I make the webservice return the json object only and not the xml headers?

Calling this webservice with header Content-Type: application/json will automatically transform the response to json and your xml will be gone.

Related

asmx service returns xml instead of json

I am trying to set up a asmx service to return json inside the web method. When I view the response inside
a browser instead of returning json I get xml. I have set up my web method to return the json format.
Please find my web service below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
namespace space_port_lander_real_app
{
/// <summary>
/// Summary description for WebService1
/// </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 WebService1 : System.Web.Services.WebService
{
[WebMethod(CacheDuration = 60)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string HelloWorld()
{
//string xmlstring = "<user><name>Hello World</name><password>some pass</password></user>";
//var name = $(xml).find('name').text();
//return xmlstring;
return "hello world";
}
}
}
The response output looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<string xmlns="http://tempuri.org/">hello world</string>
I set up my method to return a string. Is there something I'm missing?
If you want a GET method to return JSON, you need to set it otherwise use POST.
[ScriptMethod(UseHttpGet=true, ResponseFormat = ResponseFormat.Json)]
Check Here

SOAP Request format

I am trying to create a SOAP web service to use with a client.
According to the documentation, we have to create a web service with two methods that return certain information. I have created them without a problem, but I can not get them to fit the example format.
I have to say that for years I did not create any SOAP services (since Net 2.0) because I have been doing REST services for a long, so if you see any nonsense, forgive me.
The example request that there is in the documentation (the good one) is this:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:pag="http://pagorecibos.pagosrecibos.com/">
<soapenv:Header/>
<soapenv:Body>
<pag:obtenerImporte>
<referencia>040</referencia>
</pag:obtenerImporte>
</soapenv:Body>
</soapenv:Envelope>
That's the format that my service want to recieve:
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<obtenerImporte xmlns="http://tempuri.org/">
<referencia>string</referencia>
</obtenerImporte>
</soap:Body>
</soap:Envelope>
The code of my service is this:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service: System.Web.Services.WebService
{
[WebMethod]
[SoapDocumentMethod(ParameterStyle = SoapParameterStyle.Bare)]
public string ObtenerImporte(ObtenerImporte obtenerImporte)
{
return "Hola a todos";
}
[WebMethod]
[SoapDocumentMethod(ParameterStyle = SoapParameterStyle.Bare)]
public string RealizarPago(RealizarPago realizarPago)
{
return "Hola a todos";
}
}
Class (the other class is similar):
public class ObtenerImporte
{
[XmlElement("referencia")]
public string Referencia { get; set; }
}
The difference is in the namespace and the prefix in node "obtenerImporte" but I can't resolve it.
I'm using VS2017 Community Edition y created the project using "ASP.NET Web Service" template.
Problem solved!!!. Adding and removing code.... suddenly it works :D. The right way to define the service is this (thanks #zaitsman for your clue):
[WebService(Namespace = "http://pagorecibos.pagosrecibos.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class Service : System.Web.Services.WebService
{
[WebMethod]
[SoapDocumentMethod(Use = SoapBindingUse.Literal, ParameterStyle = SoapParameterStyle.Bare)]
public string ObtenerImporte(ObtenerImporte obtenerImporte)
{
return "Obtener Importe";
}
[WebMethod]
[SoapDocumentMethod(ParameterStyle = SoapParameterStyle.Bare)]
public string RealizarPago(RealizarPago realizarPago)
{
return "Realizar Pago";
}
}
I hope that this solution could help other one.

Asp.net webservice always recieving null values from soap ui

I'm posting below message from soap UI and i always receiving null value in webservice. Whatever message I'm posting from soap UI it is taking as null only.
<?xml version="1.0" encoding="UTF-8"?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
<env:Header/>
<env:Body>
Test
</env:Body>
</env:Envelope>
Below is my simple WebService
[WebService(Namespace = "http://test.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class TestService : System.Web.Services.WebService {
[WebMethod]
public int TestMethod(string message)
{
try
{
File.WriteAllText("D:\\abc.xml", message);
return 0;
}
catch (Exception ex)
{
return 1;
}
}
}
You're not specifying which method to call or the parameters of that method in your body. You'll need something like this:
<env:Body>
<m:TestMethod xmlns:m="http://tempuri.org">
<message>Test</message>
</m:TestMethod>
</env:Body>

Error during rebuilding ASMX Web Service

I'm trying to publish my web service, i have already changed Build Action properties of .asmx file to "Compile" and Web.config to "None" but still i get following errors when im trying to rebuild solution:
Error 1 Keyword, identifier, or string expected after verbatim specifier: # \MyVirtualCartWS\MyVirtualCartWS.asmx
Error 2 A namespace cannot directly contain members such as fields or methods \MyVirtualCartWS\MyVirtualCartWS.asmx
both errors points .asmx file so here it is:
<%# WebService Language="C#" CodeBehind="MyVirtualCartWS.asmx.cs" Class="MyVirtualCartWS.MyVirtualCartWS" %>
Code behind
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Collections;
namespace MyVirtualCartWS
{
/// <summary>
/// Summary description MyVirtualCartWS
/// </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 MyVirtualCartWS : System.Web.Services.WebService
{
#region Using LoggedUser
[WebMethod]
public LoggedUser AddUser(string _login, string _email, string _password)
{
LoggedUser lUser = new LoggedUser();
lUser.AddUser(_login, _email, _password);
return lUser;
}
[WebMethod]
public LoggedUser LogIn(string _login, string _password)
{
LoggedUser lUser = new LoggedUser();
lUser.LogIn(_login, _password);
return lUser;
}
#endregion
}
}
The line:
[System.Web.Script.Services.ScriptService]
should be uncomment first.

How to access a web service with overloaded methods

I'm trying to have overloaded methods in a web service but I am getting a System.InvalidOperationException when attempting "Add Web Reference" in Visual Studio 2005 (here's the relevant snippets of code):
public class FileService : System.Web.Services.WebService
{
private static readonly MetaData[] EmptyMetaData = new MetaData[0];
public FileService()
{
// a few innocent lines of constructor code here...
}
[WebMethod(MessageName = "UploadFileBasic",
Description = "Upload a file with no metadata properties")]
public string UploadFile(string trimURL
, byte[] incomingArray
, string fileName
, string TrimRecordTypeName)
{
return UploadFile(trimURL
, incomingArray
, fileName
, TrimRecordTypeName
, EmptyMetaData);
}
[WebMethod(MessageName = "UploadFile",
Description = "Upload a file with an array of metadata properties (Name/Value pairs)")]
public string UploadFile( string trimURL
, byte[] incomingArray
, string FileName
, string TrimRecordTypeName
, MetaData[] metaDataArray)
{
// body of UploadFile function here
I thought supplying a different MessageName property on the WebMethod attribute would fix this problem but here is the entire error message I get:
Both System.String UploadFileBasic(System.String, Byte[], System.String, System.String) and System.String UploadFile(System.String, Byte[], System.String, System.String) use the message name 'UploadFileBasic'. Use the MessageName property of the WebMethod custom attribute to specify unique message names for the methods.
The web service compiles OK; I cannot see what is wrong here.
My suggestion is to not use overloaded method names. There is no such concept in WSDL, so why bother?
You need to change this part:
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
to this one:
[WebServiceBinding(ConformsTo = WsiProfiles.None)]
I would generally have a class object behind the web service interface that has the overloaded methods and then create individual methods in your asmx.cs file with different names. I know you can use the attributes but it just makes tidier code IMHO.
Operation overloading is not allowed for web services. But you can also follow the below steps.
Firstly you need to change
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
To
[WebServiceBinding(ConformsTo = WsiProfiles.None)]
Secondly MessageName property of WebMethod should be different for Overloaded method.
namespace foo
{
/// <summary>
/// Summary description for TestService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.None)]
[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 TestService : System.Web.Services.WebService
{
[WebMethod(MessageName = "HelloWorld1")]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod(MessageName = "HelloWorld2")]
public string HelloWorld(string Value = "default")
{
return "Hello World";
}
}
}
But if you will call URL Like:
http://localhost:15558/TestService.asmx/HelloWorld2?Value=2
It will work.
But if you will call URL Like:
http://localhost:15558/TestService.asmx/HelloWorld?Value=2
It will display HTTP 500

Categories