my c# code to call webservice -
var content = new StringContent(req.Body.ToString(), Encoding.UTF8, "application/xml"); ;
HttpClient httpClient = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://mydemo.com/service.asmx?pk=listCustomer");
var byteArray = Encoding.ASCII.GetBytes("username:password");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
request.Content = content;
request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/xml");
HttpResponseMessage response = await httpClient.SendAsync(request);
// getting 500 error in response data at root level invalid
in postman i call this azure function to pass xml input.
xml input format is -
<?xml version="1.0" encoding="utf-8"?>
<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>
<listCustomer xmlns="http://tempuri.org/">
<id>KH001</id>
<fromDate>01/01/2018</fromDate>
<toDate>01/01/2020</toDate>
</listCustomer>
</soap:Body>
</soap:Envelope>
I test function on the local with postman, below is my code. Maybe you could have a try.
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
return new ContentResult { Content = requestBody, ContentType = "application/xml" };
}
And the content type would be right.
Related
[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
var data = new { key = key, id = req.Query["mailid"] };
var result = await myHttpClient.PostAsJsonAsync("https://someapi.com/api/info", data);
return new OkObjectResult(result);
}
Hi.
Im trying to build an azure function, which gets the variable mailid and sends a POST request to an API with the apikey and the mailID in a body, so it can check the status of the mail and give back if its delivered or not. I dont get it to work and "result" returns a json of the httpClient, with the error code 500. Why doesnt the request work? The API expects the key and id in a JSON format in the POST-body.
[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string mailid = req.Query["mailid"];
var data = new Dictionary<string, string> {
{ "key", key },
{ "id", mailid },
};
//var data = new { key = key, id = req.Query["mailid"] };
var json = JsonConvert.SerializeObject(data, Formatting.Indented);
var stringContent = new StringContent(json);
myHttpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var result = await myHttpClient.PostAsync("https://someapi.com/api/info", stringContent);
var responseString = await result.Content.ReadAsStringAsync();
return new OkObjectResult(responseString);
}
I just got it to work without an anonymous type variable, which the senior advised me to use. This gets me the result I wanted. It seems like it didnt get send in the proper post-body, as a proper json.
I am new to WEB API and I have created a get and a post method the get is working however the the parameter in the post is returning null.
The code for request is
if (ModelState.IsValid)
{
var client = new RestClient(string.Format("{0}/api/order/createorder",Baseurl));
client.Timeout = -1;
var request = new RestRequest(Method.POST);
var test = JsonConvert.SerializeObject(order);
request.AddJsonBody(order);
IRestResponse response = client.Execute(request);
and it points to the following method
[HttpPost]
[Route("api/order/createorder")]
public HttpResponseMessage AddOrder([FromBody]IOrder order)
{
if(order== null)
{
var resp = new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new StringContent("The order is a required parameter"),
ReasonPhrase = "Order not present"
};
throw new HttpResponseException(resp);
}
I have added the <requestLimits maxAllowedContentLength="4294967295" /> to the web config but to no avail.
Can anyone point me to what I am doing wrong with the request?
Cheers
Try this code
var client = new RestClient(string.Format("{0}/api/order/createorder",Baseurl));
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json; charset=utf-8");
var body = JsonConvert.SerializeObject(order);
request.AddParameter("application/json; charset=utf-8", body, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var result = response.Content;
and never use interfaces in action parameters, since the action needs to create an object, but it is impossible from interface
[Route("~/api/order/createorder")]
public HttpResponseMessage AddOrder([FromBody] Order order)
I think if can rewrite you request to this ->
var client = new RestClient("/api/order/createorder",Method.Post, DataFormat.Json);
client.AddJsonBody(order);
IRestResponse response = client.Execute(request);
That might just work, you may need some mapping potentially if the payload you are passing to the controller is a different type.
Here is what the header is supposed to look like
<soap:Header>
<AuthenticationHeader>
<UserName>string</UserName>
<Password>string</Password>
</AuthenticationHeader>
</soap:Header>
Here is what I've tried:
string username = "TheUserName";
string password = "ThePassword";
HttpRequestMessage requestMessage = new HttpRequestMessage(method, uri);
requestMessage.Headers.Add("UserName", username);
requestMessage.Headers.Add("Password", password);
Maybe I have to somehow set the authorization header?
requestMessage.Headers.Authorization = ??
I feel like somehow I have to "build" that AuthenticationHeader element but I'm not sure how to do that. Any suggestions?
Edit: Full SOAP Envelope
?xml version="1.0" encoding="utf-8"?>
<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:Header>
<AuthenticationHeader xmlns="http://www.test.com/testing/Security">
<UserName>string</UserName>
<Password>string</Password>
</AuthenticationHeader>
</soap:Header>
<soap:Body>
<GetMeSomething xmlns="http://www.test.com/testing/WorkFileCatalog">
<Param1>string</Param1>
<Param2>string</Param2>
<XMLRetMess>string</XMLRetMess>
</GetMeSomething>
</soap:Body>
</soap:Envelope>
Given the provided OP, the following Unit Test was done as a proof of concept of how you can populate the header message header and create a request.
[TestClass]
public class SOAP_UnitTests {
private HttpMethod method;
private string uri;
private string action;
[TestMethod]
public void _Add_SOAP_Auth_Header_Details_With_HttpRequestMessage() {
string username = "TheUserName";
string password = "ThePassword";
var xml = ConstructSoapEnvelope();
var doc = XDocument.Parse(xml);
var authHeader = doc.Descendants("{http://www.test.com/testing/Security}AuthenticationHeader").FirstOrDefault();
if (authHeader != null) {
authHeader.Element(authHeader.GetDefaultNamespace() + "UserName").Value = username;
authHeader.Element(authHeader.GetDefaultNamespace() + "Password").Value = password;
}
string envelope = doc.ToString();
var request = CreateRequest(method, uri, action, doc);
request.Content = new StringContent(envelope, Encoding.UTF8, "text/xml");
//request is now ready to be sent via HttpClient
//client.SendAsync(request);
}
private static HttpRequestMessage CreateRequest(HttpMethod method, string url, string action, XDocument soapEnvelopeXml) {
var request = new HttpRequestMessage(method: method, requestUri: url);
request.Headers.Add("SOAPAction", action);
request.Headers.Add("ContentType", "text/xml;charset=\"utf-8\"");
request.Headers.Add("Accept", "text/xml");
request.Content = new StringContent(soapEnvelopeXml.ToString(), Encoding.UTF8, "text/xml"); ;
return request;
}
private string ConstructSoapEnvelope() {
var message = #"<?xml version='1.0' encoding='utf-8'?>
<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:Header>
<AuthenticationHeader xmlns='http://www.test.com/testing/Security'>
<UserName>string</UserName>
<Password>string</Password>
</AuthenticationHeader>
</soap:Header>
<soap:Body>
<GetMeSomething xmlns='http://www.test.com/testing/WorkFileCatalog'>
<Param1>string</Param1>
<Param2>string</Param2>
<XMLRetMess>string</XMLRetMess>
</GetMeSomething>
</soap:Body>
</soap:Envelope>
";
return message;
}
}
If you are using HttpClient to POST a request, then you should build the full XML request.
In other words, you would build the exact Soap XML including all the elements
string requestXml = your actual full soap xml
string result = HttpClient.Post ( your actual xml )
MainViewModel:
public async Task<string> Httpclient(string link,string oauthToken)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", oauthToken);
HttpResponseMessage response = await client.PostAsync(link,new StringContent(""));
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
return await response.Content.ReadAsStringAsync();
}
Get_account_ViewModel:
public class Get_Current_Account_ViewModel
{
MainViewModel mainViewModel = new MainViewModel();
public async Task<Model.Get_Current_Account.RootObject> get_current_account(string _accessToken)
{
var query = await mainViewModel.Httpclient("https://api.dropboxapi.com/2/users/get_current_account?access_token=_accessToken",_accessToken);
if (query != null)
{
var get_data = JsonConvert.DeserializeObject<Model.Get_Current_Account.RootObject>(query);
return get_data;
}
else
return null;
}
I tried on two ways:
the first way: I got a problem is
Error in call to API function "users/get_current_account": Unexpected URL params: "access_token" on Dropbox API
at
var query = await mainViewModel.Httpclient("https://api.dropboxapi.com/2/users/get_current_account?access_token=_accessToken",_accessToken);
second way: Error in call to API function "users/get_current_account": Bad HTTP "Content-Type" header: "text/plain; charset=utf-8". Expecting one of "application/json", "application/json; charset=utf-8", "text/plain; charset=dropbox-cors-hack". when I remove ?access_token=_accessToken at var query.
Please everyone solve this problem. I can not fix it. thanks.
You were right to get rid of the access_token parameter, since, as the error says, that's not a valid parameter.
The next error indicates that you're sending the wrong Content-Type header, so try sending the right one. E.g.
HttpResponseMessage response = await client.PostAsync(
link, new StringContent("", System.Text.Encoding.UTF8, "application/json"));
(This code is untested, just reading the docs on StringContent.)
When I call serever like this:
var client = new RestClient();
client.Authenticator = new NtlmAuthenticator();
var request = new RestRequest(uri);
request.Method = Method.POST;
request.RequestFormat = DataFormat.Xml;
request.AddParameter("application/atom+xml", doc /*some xml document*/, ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
Debug.WriteLine(response.Content);
if(response.StatusCode == HttpStatusCode.Created)
{
// always 401
}
I get next server responce:
<?xml version="1.0" encoding="UTF-8"?>
<SmoothStreaming xmlns="http://schemas.microsoft.com/iis/media/2011/03/streaming/management">
<Error>
<ErrorCode>0x80880022</ErrorCode>
<ErrorMessage>All requests to the management APIs must be authenticated. Please install and enable an appropriate IIS authentication module for this website.</ErrorMessage>
</Error>
</SmoothStreaming>
What and where should I change (install)?