how to get response from the xml web Api - asp.net-core-webapi

I have XML Web API like this
http://test/REST?hiInstanceId=7
XML parameters
<request_info>SALE</request_info><location_id>36</location_id>
<from_dt>01-JUN-22</from_dt><to_dt>10-JUN-22</to_dt>
how to get the response from the XML web API?  

how to get response from the xml web Api
To make the Asp.net Core API return the XML format response. We need to configure XML formatters implemented using XmlSerializer, call AddXmlSerializerFormatters:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers()
.AddXmlSerializerFormatters();
Then, in the API controller, use the [Produces] attribute to specify a format.
[Route("api/[controller]")]
[ApiController]
public class TodoController : ControllerBase
{
[HttpGet]
[Produces("application/xml")]
public TestModel GetCustomers( )
{
return new TestModel()
{
request_info = "Sale",
location_id = 36,
from_dt = "01-JUN-22",
to_dt = "10-JUN-22"
};
}
}
Then, use the following code to call the API method and get the XML response:
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(new Uri("https://localhost:44374/api/todo"));
httpRequest.ContentType = "application/xml";
httpRequest.Method = "Get";
using (HttpWebResponse httpResponse = (HttpWebResponse)httpRequest.GetResponse())
{
using (Stream stream = httpResponse.GetResponseStream())
{
string xml = (new StreamReader(stream)).ReadToEnd(); //get the XML response
//Using XMLSerializer to convert the XML response to the object.
XmlSerializer serializer = new XmlSerializer(typeof(TestModel));
StringReader rdr = new StringReader(xml);
var result = (TestModel)serializer.Deserialize(rdr);
}
}
The debug screenshot like this:

Related

Web API PUT,DELETE, POST methods via URI

I am very new to the whole consept of API's. So far, I managed to build a web api that has GET,POST,PUT and DELETE methods.
Now, from an ASP.NET project, I try to finally use my web api.
Here's what I do for GET method:
string info = new WebClient() { }.DownloadString("https://mywebapisite.com/item/" + id);
Item item = JsonConvert.DeserializeObject<Item>(info);
This functions all fine. As you can see, all the GET method needs is an id.
However, for the POST method, I have no clue what to do.
I can create a new Item instance, but don't know what to do with it.
By the way, I also used ASP.NET to make my web.api.
There is a built-in feature in ASP.NET 5 called Swagger. It can perform all the tasks very succesfully. Is there like a code-behind for what Swagger does.
PS: I know that this question must be very common and basic. If you could refer me to another question in stackoverflow or simply tell me what to search on google I would appreciate it. (As you may guess, I don't even know what to search for)
pseudo code to consume post request in C#
var requestObj = GetDummyDataTable();
using (var client = new HttpClient())
{
// Setting Base address.
client.BaseAddress = new Uri("https://localhost:8080/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = new HttpResponseMessage();
// HTTP POST
response = await client.PostAsJsonAsync("api/product", requestObj).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
// Reading Response.
string result = response.Content.ReadAsStringAsync().Result;
var responseObj = JsonConvert.DeserializeObject<DataTable>(result);
}
}
You can refer the following code to call the API using HttpClient:
////using System.Net.Http.Headers;
////using System.Text;
using (var client = new HttpClient())
{
var requesturi = "https://localhost:7110/api/ToDo/relativeAddress";
var item = new TestUserViewModel()
{
Name = "John Doe",
Age = 33
};
////using System.Text.Json; // use JsonSerializer.Serialize method to convert the object to Json string.
StringContent content = new StringContent(JsonSerializer.Serialize(item), Encoding.UTF8, "application/json");
//HTTP POST
var postTask = client.PostAsync(requesturi, content);
postTask.Wait();
var result = postTask.Result;
if (result.IsSuccessStatusCode)
{
var Content = await postTask.Result.Content.ReadAsStringAsync();
return RedirectToAction("Privacy");
}
}
The API method like this:
[Route("api/[controller]")]
[ApiController]
public class TodoController : ControllerBase
{
[HttpPost]
[Route("relativeAddress")]
public string GetAddress([FromBody] TestUserViewModel testUser)
{
return "Address A";
}
And the result like this:
You can also refer this link to set the Content-Type.
You seem a little bit lost, and I get it. Api learning path is kinda weird, I recommend you watch a tutorial (My favorite https://www.youtube.com/playlist?list=PLLWMQd6PeGY0bEMxObA6dtYXuJOGfxSPx)
But if you need code asap, you could refer the following code.
Ps: The others answers are really good!
using System.Net.Http;
using System.Net.Http.Headers;
public class ApiHelper
{
public HttpClient ApiClient { get; set; }
public void InitializeClient()
{
ApiClient = new HttpClient();
ApiClient.BaseAddress = new Uri("https://mywebapisite.com/");
ApiClient.DefaultRequestHeaders.Accept.Clear();
ApiClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task PostSomething(FormUrlEncodedContent data)
{
using (HttpResponseMessage response = await ApiClient.PostAsync("/item",data)
{
var result = await response.Content.ReadAsAsync<string>();
}
}
}

XmlSerialization not working in .NET Core 2

I have .NET Core 2.0 application. The Code below serializes the object using XmlSerializer and POST the content to api. (default is DataContractSerializer so i am explicitly passing XmlSerializer)
// use XmlSerializer
var formatter = new XmlMediaTypeFormatter();
formatter.UseXmlSerializer = true;
// Post as Xml
var httpResponse = await httpClient.PostAsync<TSource>(url, source, formatter).ConfigureAwait(false);
Here the request object
[XmlRoot(ElementName = "Request", Namespace = "")]
public class RequestDTO
{
[XmlArray("Invoices")]
[XmlArrayItem("InvoiceId")]
public string[] Invoices { get; set; }
}
However POST fails with HTTP 400 error. When i check the request in fiddler i noticed the following
so serialization wrapping the actual request around bd and o.
Not sure why?

Pass LIST object by Rest API Client to Web API 2 using JSON

I have a problem in pass data list from Client to the Web API 2 by JSON.
Here are my code samples
Client
string RestUrl = "http://***SrviceUrl***/api/InvoiceHeader/{0}";
var uri = new Uri(string.Format(RestUrl, string.Empty));
List<InvItem> myList = new List<InvItem>(Common.invitems);
var json = JsonConvert.SerializeObject(myList);
var content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = null;
response = await client.PutAsync(uri ,content);
if (response.IsSuccessStatusCode)
{
Debug.WriteLine(#"successfully saved.");
}
Web Service - Controller class
[HttpPut]
[BasicAuthentication(RequireSsl = false)]
public HttpResponseMessage Put(string item)
{
List<InvItemToSave> myList = new List<InvItemToSave>();
myList = JsonConvert.DeserializeObject<List<InvItemToSave>>(item);
try
{
todoService.InsertInvoiceDetail(myList);
}
catch (Exception)
{
return base.BuildErrorResult(HttpStatusCode.BadRequest, ErrorCode.CouldNotCreateItem.ToString());
}
return base.BuildSuccessResult(HttpStatusCode.Created);
}
when i try to pass single data object to same controller it works fine.
but for LIST objects it returns error code.
StatusCode: 405, ReasonPhrase: 'Method Not Allowed'
I tried to pass exact same * list content* through third party REST client . It returned success code.
You are doing a PutAsync into a HttpPost action. Your api URL looks incorrect as well, should be,
http://***SrviceUrl***/api/InvoiceHeader
and action should be,
public HttpResponseMessage Put(List<InvItem> items)

REST WEBAPI POST method with parameters not being called

I have built a REST API with a controller having a POST method with 4 parameters like this-
[HttpPost]
public void SaveSession([FromBody] string userId, [FromBody] DateTime issueDateTime, [FromBody] string browserType, [FromBody] string salt)
{
// Params need to be changed
_sessionService.SaveSession(userId, issueDateTime, browserType, salt);
}
How should I POST data on the client side, I mean what should be the format of the data to be sent?
I tried this format-
"userId=abc&DateTime=someDatetime&browserType=somebrowser&salt=somesalt"
Its not working if I try this, The web service method is not even being called
Could anyone tell me the correct format?
EDIT:
Here is how I am calling the API-
const string endPoint = #"http://localhost:85/session/Test";
var postData = "userId=abc&DateTime=someDatetime&browserType=somebrowser&salt=somesalt"
var request = (HttpWebRequest) WebRequest.Create(EndPoint + parameters);
request.Method = "POST";
request.ContentLength = 0;
request.ContentType = "application/x-www-form-urlencoded";
if (!string.IsNullOrEmpty(postData) && Method == HttpVerb.POST)
{
var encoding = new UTF8Encoding();
var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(postData);
request.ContentLength = bytes.Length;
using (var writeStream = request.GetRequestStream())
{
writeStream.Write(bytes, 0, bytes.Length);
}
}
using (var response = (HttpWebResponse) request.GetResponse())
{
var xmlDoc = new XmlDocument();
if (response.StatusCode != HttpStatusCode.OK)
{
var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
throw new ApplicationException(message);
}
// grab the response
var responseStream = response.GetResponseStream();
if (responseStream != null)
{
xmlDoc.Load(responseStream);
}
return (xmlDoc);
}
Thanks!
I assume routing has been properly configured.
Said so.... DateTime parameter in the controller method has been named "issueDateTime" while within the request has been named "DateTime".
I got to know, what mistake I was doing. I was sending 4 parameters in a WebService method. We can only send one parameter while calling a web service method. If you want to send multiple data, just send it as an object. Like this -
[HttpPost]
public void SaveSession([FromBody] Values value)
{
var userId = values.userId,
var issueDateTime= values.issueDateTime,
var browserType= values.browserType,
var salt= values.salt,
_sessionService.SaveSession(userId, issueDateTime, browserType, salt);
}

Streaming webservice call in flex

I am trying to create a file upload in a flex/air application that sends information to a .NET wcf SOAP webservice. The file upload also has to have progress indicating events. The service uses a Stream as a MessageBodyMember to allow streaming upload. My input looks a little like this:
[MessageContract]
public class SendFileRequestMessage : IDisposable
{
public string UserName;
[MessageBodyMember(Order = 1)]
public Stream FileData;
}
and the service looks like this:
public interface IFileTransferService
{
[OperationContract]
SendFileResponseMessage SendFile(SendFileRequestMessage request);
}
Now when i create a proxy class in VS2010 i get a Stream object for FileData. If I do the same in Flash Builder 4.7 the FileData is interpreted as a ByteArray. I already looked into FileUpload and UrlLoader in my client but i can't get the body member set. My action script now looks like this
not working
var dataToSave:XML = <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:q0="http://mystuff/uploadservice/v1"><soapenv:Body><q0:SendFile/></soapenv:Body></soapenv:Envelope>
var request:URLRequest = new URLRequest("http://localhost:31454/Uploadhandler.svc");
request.requestHeaders = new Array(new URLRequestHeader("SOAPAction", "http://mystuff/uploadservice/v1/IFileTransferService/SendFile"));
request.data = dataToSave;
request.contentType = "text/xml; charset=utf-8";
request.method = URLRequestMethod.POST;
var loader:URLLoader = new URLLoader();
loader.load(request);
So how can do a streaming file upload to a soap service from flex? Any help would be very appreciated.
I'm not familiar with .NET SOAP model, but if it expects standard http content dispositions for file data you can try getting FileReference object for your file and then pass your URLRequiest in its upload method. In your case this could be like
... Create class level variable ...
var fr:FileReference = new FileReference();
... Obtain file reference somewhere ...
//Set handlers for Filereference events
fr.browse(); //Obtain actual file reference
... Somewhere in selectHandler chain....
var dataToSave:XML = <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:q0="http://mystuff/uploadservice/v1"><soapenv:Body><q0:SendFile/></soapenv:Body></soapenv:Envelope>
var request:URLRequest = new URLRequest("http://localhost:31454/Uploadhandler.svc");
request.requestHeaders = new Array(new URLRequestHeader("SOAPAction", "http://mystuff/uploadservice/v1/IFileTransferService/SendFile"));
request.data = dataToSave;
request.contentType = "text/xml; charset=utf-8";
request.method = URLRequestMethod.POST;
//Do POST
fr.upload(request);
This Documentation contains examples for using FileReference.

Resources