How can i consume web api in asp.net MVC - asp.net

I am new to .Net MVC. I am trying to create a sample CRUD application using Web APIs created in NodeJS.
Reading data from DB(MSSQL) is working fine using the below code in .net MVC
List<student> students = new List<student> { };
HttpResponseMessage response = await client.GetAsync(path);
if (response.IsSuccessStatusCode)
{
students = await response.Content.ReadAsAsync<List<student>>();
}
I want to update the record in DB by consuming the node api in .net MVC. I am using the below code, but its not working,
HttpResponseMessage response = await client.PutAsJsonAsync(
"localhost:8082/update", data);
response.EnsureSuccessStatusCode();
student std = await response.Content.ReadAsAsync<student>();
I want to know how can i consume a web api with PUT method.
Any Help would be appreciated!

Related

Integrate RazorPay UPI in ASP.Net to fetch bank details by IFSC code

I want to integrate web api of RazorPay by which I will get the bank details by providing the IFSC code.
I have a code which works fine in ASP.Net Core but not working in ASP.Net 4.7.
ASP.Net core code:
using (var httpClient = new HttpClient())
{
using (var response = await httpClient.GetAsync($"https://ifsc.razorpay.com/{ifsc}"))
{
string apiResponse = await response.Content.ReadAsStringAsync();
bank = JsonConvert.DeserializeObject<BankModel>(apiResponse);
}
}
}
Source URL: https://www.techstackexperts.com/2020/05/complete-example-of-razorpay-api-to-get.html?showComment=1609738264273#c1227651246871561148
in Response.Content I am getting an error. Please advise, asp.net relevant code for the same.

Uploading File (IfromFile) via HttpClient To webApi

Need help. I am trying to save or uploud a file (IFormFile) from a Project Web to the Web Api, consuming the web api via httpClient. I am getting the following error: System.NotSupportedException: The collection type 'Microsoft.AspNetCore.Http.IHeaderDictionary' on 'Microsoft.AspNetCore.Http.IFormFile.Headers' is not supported.enter image description here
enter image description here
NotSupportedException: The collection type 'Microsoft.AspNetCore.Http.IHeaderDictionary' on 'Microsoft.AspNetCore.Http.IFormFile.Headers' is not supported.
It seems that you are serializing a FormFile, which cause the above issue.
I am trying to save or uploud a file (IFormFile) from a Project Web to the Web Api, consuming the web api via httpClient.
public async Task<IActionResult> Online([FromForm]CandidaturaAddModel model)
{
var formContent = new MultipartFormDataContent();
formContent.Add(new StringContent(model.Senha), "Senha");
formContent.Add(new StringContent(System.Text.Json.JsonSerializer.Serialize(model.AnoLectvo)), "AnoLectvo");
//...
//for other properties, such as Email, Genero etc
//...
formContent.Add(new StreamContent(model.Foto.OpenReadStream()), "Foto", Path.GetFileName(model.Foto.FileName));
_httpClient.BaseAddress = new Uri("https://localhost:xxxx/");
var response = await _httpClient.PostAsync("/api/xxx/CandidaturaAdd", formContent);
if (response.IsSuccessStatusCode)
{
//....
}
Test Result

Unable to call API's from ASP.NET MVC App?

I've created a API where I want to call another API from, for testing im using Pokemon API with PostMan. However when I want to call this API im my own API application getting an error. Code executed when API is getting called:
[System.Web.Http.AcceptVerbs("GET")]
[System.Web.Http.HttpGet]
[System.Web.Http.Route("RedirectApi")]
public async Task<object> getCall()
{
checkAuthorisation();
setVariables();
if (isAuthorized == true)
{
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.GetAsync("https://pokeapi.co/api/v2/pokemon/ditto/");
var code = response.StatusCode;
response.EnsureSuccessStatusCode();
string responseBody = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject(responseBody);
}
else
{
return JsonConvert.DeserializeObject("Unauthorized");
}
}
Im calling my API with this link:
http://localhost:54857/GetPokemon
Whenever I execute this using Postman in debug mode it executes but fails on this code:
HttpResponseMessage response = await client.GetAsync("https:/pokeapi.co/api/v2/pokemon/ditto/");
It also does not give me any feedback except what Postman gives me back:
Hope someone can help!
Thanks in advance!

How to consume restful services from another restful service in asp.net?

I have an URL of one restful service, I want to consume this restful service from another restful service.
Suppose URL is first rest service is "http://testapi.com/services/rest/?method=getList&key=123”
Restful service 1 - > Restful service 2 -> asp.net client application
Could you provide any example with code and configuration settings.
Thanks
You can use the HttpClient. The example in the post is using a console application, but you can still use it from a Web Api project (which I have on some of my projects).
Example get async:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("YOURURIHERE");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// New code:
HttpResponseMessage response = await client.GetAsync("api/products/1");
if (response.IsSuccessStatusCode)
{
Product product = await response.Content.ReadAsAsync>Product>();
}
}

How to consume a secure Rest MVC web api

I'm just a beginner on the .NET world and I've created a web api (.NET 4.5.2) and I'm using the annotation [Authorize] above my controllers like shown below:
[Authorize]
public class PhasesController : ApiController
{
private TestReportEntities db = new TestReportEntities();
// GET: api/Phases
public IQueryable<Phase> GetPhase()
{
return db.Phase;
}
}
I've already created my DB and I'm using the default tables that the web.api uses to manage the access, as you can see on this image:
My tables
I've already done a method to request to my web api, in another project/solution, it's working fine when I remove the annotation [Authorize] from my web api controllers.
this is an example about how I'm requesting my api:
public int GetCurrentIdPhase(int idProject)
{
int phaseId = -1;
WebRequest request = WebRequest.Create(string.Concat(URL, string.Format("api/phases/?idProject={0}", idProject)));
using (var resp = (HttpWebResponse)request.GetResponse())
{
using (var reader = new StreamReader(resp.GetResponseStream()))
{
string objText = reader.ReadToEnd();
var phase = JsonConvert.DeserializeObject<List<Phase>>(objText);
phaseId = phase[0].id;
}
}
if (phaseId != -1)
{
return phaseId;
}
else
{
throw new Exception("Phase not found");
}
}
At the end of the day my questions are:
How can I request a token to my api (POST - www.myApi/token) using the example above?
How can I use the token, once I've got it, on every request to my API?
if you can help me I would really appreciate it.
Thanks.
I've created a method to get the Token from my Web API, this is the method:
var request = (HttpWebRequest)WebRequest.Create(string.Concat(URL, "token"));
var postData = "grant_type=password";
postData += string.Format("&userName={0}", user);
postData += string.Format("&password={0}", pass);
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
string objText = new StreamReader(response.GetResponseStream()).ReadToEnd();
var requestedToken = (JObject)JsonConvert.DeserializeObject(objText);
token = string.Concat(token, requestedToken["access_token"].Value<string>());
And to request something to my API all I need to do is just add the token on the header of all requests like shown on the line below:
request.Headers.Add(HttpRequestHeader.Authorization, getToke());
Hope it can help someone else who is beginning to work with .NET web API like me.
Regards.
Im assuming the "GetCurrentIdPhase" call is from an unrelated app with unrealted auth - if any auth.
The difficulty here is in using Authorize and the traidtional browser authentication flow. Here's an example of changing the pipeline a bit to use a different auth form for using console/desktop apps. You don't say where you are calling GetCurrentIdPhase from so I'll have to assume either a separate app. If its a web app and you are authenticated using the same tables, then you will have to share the token between them using for ex. the url blackice provided above.
If the app is a desktop/console/etc (not another app that the user had to auth against the same tables) then you can try this approach to change how auth is done to make it easier to access.
MVC WebAPI authentication from Windows Forms

Resources