Friday, 14 June 2019

MVC - Web Service - Create Web Service - Pass XML file (not string) as Parameter and Receive XML file (not string) in Web Service

Watch this example on YouTube



1. Web Service

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Xml;

namespace WebApplication15
{
    /// <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]
        public string HelloWorld()
        {
            return "Hello World";
        }

        [WebMethod]
        public string XMLTest(XmlDocument doc)
        {
            var xmlString = doc.InnerText;
            return "success";
        }

    }
}

2. Consumer

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml;

namespace WebApplication16.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            XmlDocument doc = new XmlDocument();
            XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
            doc.AppendChild(docNode);

            XmlNode usersNode = doc.CreateElement("Users");
            doc.AppendChild(usersNode);

            XmlNode userNode = doc.CreateElement("User");
            XmlAttribute userAttribute = doc.CreateAttribute("ID");
            userAttribute.Value = "1";
            userNode.Attributes.Append(userAttribute);
            usersNode.AppendChild(userNode);

            XmlNode nameNode = doc.CreateElement("Name");
            nameNode.AppendChild(doc.CreateTextNode("Frank"));
            userNode.AppendChild(nameNode);
            XmlNode addressNode = doc.CreateElement("Address");
            addressNode.AppendChild(doc.CreateTextNode("1 Main St."));
            userNode.AppendChild(addressNode);

            localhost.WebService1 testService = new localhost.WebService1();
            var res = testService.XMLTest(doc);

            return View();
        }

No comments:

Post a Comment