I am using an async web method to fetch data from an external URL. I am using this web service as reference in another asp.net web application.But the web methods which are async are not returning any value.How to call an async web method in asp.net web application.
My web method code
[WebMethod]
public async Task<string> GetTrID()
{
var uri = new System.Uri("//URL");
var json = JsonConvert.SerializeObject(new { //values});
var response = await fnabc(uri, HttpMethod.Post, json, 120);
var content = await response.Content.ReadAsStringAsync();
System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();
var objValidate = js.Deserialize<class>(content);
return objValidate.RespObj;
}
private async Task<HttpResponseMessage> fnabc(Uri uri, HttpMethod method, string json, int timeOut)
{
HttpClient client = new HttpClient();
client.MaxResponseContentBufferSize = int.MaxValue;
client.Timeout = TimeSpan.FromSeconds(timeOut);
var request = new HttpRequestMessage(method, uri);
request.Headers.Accept.Clear();
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
request.Content = new StringContent(json, Encoding.UTF8, "application/json");
var response = new HttpResponseMessage();
HttpContent objCnt = new StringContent(json,Encoding.UTF8, "application/json");
response = client.PostAsync(uri.ToString(), objCnt).Result;
return response;
}
Related
This is my code using the RestSharp library:
var client = new RestClient("https://example.com/api");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer token...");
request.AddHeader("Content-Type", "text/plain");
request.AddParameter("text/plain", "{{\"post\":{{\"contact\":{{\"isActive\":true,\"phone\":\"99999999\"}}", ParameterType.RequestBody);
IRestResponse response = await client.ExecuteAsync(request);
// Console.WriteLine(response.Content);
// var res = response.Content;
How can I convert it to HttpClient using best practices?
You can use this:
var client = new HttpClient()
{
BaseAddress = new Uri("https://example.com"),
Timeout = TimeSpan.FromMinutes(5) //default is 90 seconds
};
client.DefaultRequestHeaders.Add("Authorization", "Bearer token...");
var body = new StringContent("{{\"post\":{{\"contact\":{{\"isActive\":true,\"phone\":\"99999999\"}}",Encoding.UTF8, "text/plain");
var response = await client.PostAsync("api", body);
var responseString = await response.Content.ReadAsStringAsync();
And for using the HttpClient in the right way I highly recommend to see this link.
I am working with xamarin.forms and System.Net.Http;
I am sending a photo using a post function which is this:
public static async Task<String> PostImagemAsync(User user)
{
using (var client = new HttpClient())
{
try
{
var values = new List<KeyValuePair<string, string>>(0);
values.Add(new KeyValuePair<string, string>("email", user.usua_login));
values.Add(new KeyValuePair<string, string>("senha", user.usua_senha));
values.Add(new KeyValuePair<string, string>("foto", user.cont_imagem));
values.Add(new KeyValuePair<string, string>("json", "1"));
var content = new FormUrlEncodedContent(values);
HttpResponseMessage response = await client.PostAsync("http://ws.neosuite.com.br/login.asmx/foto", content);
var json = response.Content.ReadAsStringAsync().Result;
json = json.Substring(json.IndexOf('['));
json = json.Substring(0, json.LastIndexOf(']') + 1);
var userImage = JsonConvert.DeserializeObject<List<User>>(json);
return userImage[0].cont_imagem;
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return null;
}
}
}
My image (foto) is a base64 And it does I get this error when I try to send it:
Invalid URI: The Uri string is too long.
How to solve that?
Without adding your POST content into url, add that to body using following code
var uri = new Uri (string.Format ("http://ws.neosuite.com.br/login.asmx/foto", string.Empty));
var json = JsonConvert.SerializeObject (user);//user object or you can create your own jason here
var content = new StringContent (json, Encoding.UTF8, "application/json");
var response = await client.PostAsync (uri, content);
I had developed one web service in SOAP format and trying to access service in asp.net using the below mentioned code.
public static void CallWebService()
{
try
{
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var _url = "https://test.in/ModelDetail/Service.asmx";
var _action = "https://test.in/ModelDetail/GetWarrantyDetails";
XmlDocument soapEnvelopeXml = CreateSoapEnvelope();
HttpWebRequest webRequest = CreateWebRequest(_url, _action);
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
// begin async call to web request.
IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);
// suspend this thread until call is complete. You might want to
// do something usefull here like update your UI.
asyncResult.AsyncWaitHandle.WaitOne();
// get the response from the completed web request.
string soapResult;
//using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
using (HttpWebResponse webResponse= (HttpWebResponse)webRequest.EndGetResponse(asyncResult))
{
using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
{
soapResult = rd.ReadToEnd();
}
Console.Write(soapResult);
}
}
catch(Exception ex) { throw ex; }
}
private static HttpWebRequest CreateWebRequest(string url, string action)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Headers.Add("SOAPAction", action);
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
return webRequest;
}
private static XmlDocument CreateSoapEnvelope()
{
XmlDocument soapEnvelop = new XmlDocument();
soapEnvelop.LoadXml(#"<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:tem='https://ndb.bmw.in/'><soapenv:Header/><soapenv:Body><tem:GetWarrantyDetails><tem:IP><demono>WBA3Y37070D45</demono></tem:IP></tem:GetWarrantyDetails></soapenv:Body></soapenv:Envelope>");
return soapEnvelop;
}
private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
}
but when i call this code i get error of The remote name could not be resolved.
Tried all method but get this error only.
What is missing or wrong i am doing?
I have a autentication with the web api working, but is using the email and password to autenticate, how can i change so that web api uses a username field and password for the autentication?
Another thing, how can i change the encrytion method for the password?
The Autentication is made this away:
public async Task<string> LoginAsync(string username, string password)
{
try
{
var keyValues = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("username", username),
new KeyValuePair<string, string>("password", password),
new KeyValuePair<string, string>("grant_type", "password")
};
Settings.Serverdown = false;
var request = new HttpRequestMessage(HttpMethod.Post, "http://192.168.44.22:56479/Token");
request.Content = new FormUrlEncodedContent(keyValues);
var client = new HttpClient();
client.Timeout = TimeSpan.FromMilliseconds(6000);
var response = await client.SendAsync(request);
var jwt = await response.Content.ReadAsStringAsync();
Settings.LoginSucess = response.IsSuccessStatusCode;
Settings.Username = username;
JObject jwtDynamic = JsonConvert.DeserializeObject<dynamic>(jwt);
var accessToken = jwtDynamic.Value<string>("access_token");
Settings.AccessToken = accessToken;
}
catch (Exception e)
{
XFToast.LongMessage("Cant reach the server");
Settings.Serverdown = true;
}
var accessToken2=Settings.AccessToken;
return accessToken2;
}
Thanks
static void Main(string[] args)
{
const string url = "https://test-api.abccc.com/api/Relayxxx.apixxxx?__token=xxxxxxxxxxxxxxxxxx";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
/* using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{\"user\":\"xxxx\"," +
"\"password\":\"yyyy\"}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}*/
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
Please help me how to call functions using this api and how can i get values from specified functions and send values to specific function.