How to call web service/web api with credential.
When call web service or web api some web service or web api is required authentication or access data or call the service. These service or web api's how to call with user name or password in asp.net.
I am explain this with example in mvc application.
Suppose you have username is "Admin", password is"Root@123" and your web service url is "https://apidomain.example.com/odata/v2/alldata('id')/?$format=json".
First of all you create a controller and action where you call the web service.
Like you create a action name is "Index" with task
public async Task<ActionResult> Index(){
return view();
}
After that you use the CredentialCache class to add the Credentials and the "Basic" authorization
Below code of the snippet is the complete code for call a web service with credentials.
I am explain this with example in mvc application.
Suppose you have username is "Admin", password is"Root@123" and your web service url is "https://apidomain.example.com/odata/v2/alldata('id')/?$format=json".
First of all you create a controller and action where you call the web service.
Like you create a action name is "Index" with task
public async Task<ActionResult> Index(){
return view();
}
After that you use the CredentialCache class to add the Credentials and the "Basic" authorization
Below code of the snippet is the complete code for call a web service with credentials.
public async Task<ActionResult> Index()
{
try
{
var credentials = new NetworkCredential("admin", "Root@123");
using (var handler = new HttpClientHandler { Credentials = credentials })
using (var client = new HttpClient(handler))
{
client.BaseAddress = new Uri("https://apidomain.example.com/odata/v2");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("alldata('id')/?$format=json");
response.EnsureSuccessStatusCode();
var returnValue = JsonConvert.DeserializeObject<RootObject>(((HttpResponseMessage)response).Content.ReadAsStringAsync().Result);
}
}
catch (Exception e)
{
throw (e);
}
return View();
}
Comments
Post a Comment