How do I tranfer data from one API to another API in ASP.NET MVC? - asp.net-mvc

I have created API-1 which reads data from a remote database. How to create an API-2 which will read the data from API-1 & display it?

You have given very limited information. Based on that I tried to give you answer. You just add another web API controller API2. As you said your API1 reading information which have httpget. So when you added API2 let see you implement httpGet in API as well and just use HttpClient service class to call API1. Below is code to in API2
using (var client = new HttpClient())
{
client.BaseAddress = new
Uri("http://localhost:XXXXX/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/json"));
//GET Method
var responseTask = client.GetAsync("api/API1");
responseTask.Wait();
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
var readTask =
result.Content.ReadAsAsync<string[]>();
}
else
{
Console.WriteLine("Internal server Error");
}
}
This is just example.

Related

How to Call Web API from Another MVC Project with two Parameter one in header and second in body

I want to call api action from from mvc project but i have an issue API action have two parameter one in header and second in body.
You create a HttpClient object and set the header parameter
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:64189/api/");
//your header parameter name and value
client.DefaultRequestHeaders.Add("hdrname", "hdrvalue");
//HTTP GET
var responseTask = client.GetAsync("youraction?param1=abc"); //Action Name
responseTask.Wait();
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
// Use your class model to receive the data from the API
var readTask = result.Content.ReadAsAsync<IList<YourModel>>();
readTask.Wait();
var r = readTask.Result;
}
else //web api sent error response
{
//log response status here..
}
}

How to create an appRoleAssignment via Microsoft Graph?

As per this documentation you should be able to create an appRoleAssignment via Microsoft Graph, however this doesn't work. In a GitHub issue I was instructed to create the issue here. We have migrated most of our code from Azure Graph API to Microsoft Graph and this is the last piece that is missing.
This finally worked for me!
There might be more optimized ways to post the JSON but I had to go to basics to make sure nothing is causing this to fail behind the scenes.
const string ROLE_ASSIGNMENT_FORMATTER = "https://graph.microsoft.com/beta/servicePrincipals/{0}/appRoleAssignments";
public static async Task AddApplicationUsers(string enterpriseAppId, string userId, string roleId)
{
HttpClient client = new HttpClient();
string url = string.Format(ROLE_ASSIGNMENT_FORMATTER, enterpriseAppId);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await GetAccessToken());
var roleAssignment = new
{
appRoleId = roleId,
principalId = userId,
resourceId = enterpriseAppId
};
var content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(roleAssignment), Encoding.UTF8, "application/json");
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = await client.PostAsync(url, content);
if (response.IsSuccessStatusCode)
{
return ;
}
else
{
throw new HttpRequestException(response.ReasonPhrase);
}
}

WebApi Client. PostAsJson

I have some strange problem. I am using Microsoft.AspNet.WebApi.Client.5.2.3 for simple .NET client for API. I want to post some data to API. I am using PostAsJsonAsync method for it.
using (var client = new HttpClient())
{
var adress = new Uri("http://localhost:28906/v1/things?access_token=SOMETOKEN");
var result = await client.PostAsJsonAsync(adress, new ThingModel() { Name = "test"});
}
When I am sending request, my uri is transformed from "http://localhost:28906/v1/things?access_token=SOMETOKEN" to "http://localhost:28906/v1/things/?access_token=SOMETOKEN" ( '/' is inserted before '?'). And request becomes wrong. How can I overcome this? In fact, how can I pass query string and json body?

ASP.NET WebAPI unable to post

I am unable to post data to a ASP.NET WebAPI server.
I can get data from the WEBAPI server. However, I am unable to post.
The following code fails to post:
response = await client.PostAsync("api/Cars", content);
Error:
StatusCode: 415, ReasonPhrase: 'Unsupported Media Type', Version: 1.1
Client:
[TestClass]
public class UnitTest1
{
// http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client
[TestMethod]
public async Task TestMethod1()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:48213/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP GET
var response = await client.GetAsync("api/Cars");
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsStringAsync();
}
// HTTP POST
using (var content = new StringContent(#"some_value"))
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
response = await client.PostAsync("api/Cars", content);
if (response.IsSuccessStatusCode)
{
Debug.WriteLine("Post was successful.");
}
}
}
WebAPI:
namespace FSharpWebAPI.Controllers
open System.Web.Http
open FSharpWebAPI.Models
type CarsController() =
inherit ApiController()
let values = [| { Make = "Ford"; Model = "Mustang" }; { Make = "Nissan"; Model = "Titan" } |]
member x.Get() = values
member x.Post(data) =
ignore
What updates do I need to make just to make a simple post?
As #Fyodor Soikin has pointed out, the Post method is generic ('a -> 'b -> unit), and ASP.NET Web API refuses to wire up such methods.
ASP.NET Web API uses convention over configuration in order to figure out how to route and handle incoming requests. If an HTTP POST arrives, it'll go hunting for a method (partially) named Post, and attempt to call it. While you could argue that if a generic method could handle the input, it'd be possible for Web API to still call it, it doesn't do that.
You'll need to add a type annotation - for example:
member x.Post(data : Car) =
ignore
That's probably still not going to be enough, because the type of that version of Post is Car -> 'a -> unit, so the return value is a generic function. I'd be surprised if Web API knows what to do with that.
The reason is that ignore is a function, and since Post doesn't invoke the function, the return value is the function itself.
If you want to ignore the input and return unit, you can simply do this:
member x.Post(data : Car) = ()
This version has the type Car -> unit, which I expect Web API will find acceptable.

ServiceStack - Posting multiple files with one POST request

I'm struggling with this issue for several hours, and I can't find any solution.
Does someone used ServiceStack to upload multiple files with one POST request?
I was trying to use PostFile:
FileInfo fi = new FileInfo("ExampleData\\XmlAPI.xml");
var client = new XmlServiceClient("http://localhost:1337");
client.PostFile<DefaultResponse>("/test", fi, "application/xml");
But here I am able to add only one file to the request.
My second shot was to use LocalHttpWebRequestFilter but inside there is only a extension method which also allows to post only one file.
Multiple File Upload APIs have been added to all .NET Service Clients in v4.0.54 that allow you to easily upload multiple streams within a single HTTP request. It supports populating Request DTO with any combination of QueryString and
POST'ed FormData in addition to multiple file upload data streams:
using (var stream1 = uploadFile1.OpenRead())
using (var stream2 = uploadFile2.OpenRead())
{
var client = new JsonServiceClient(baseUrl);
var response = client.PostFilesWithRequest<MultipleFileUploadResponse>(
"/multi-fileuploads?CustomerId=123",
new MultipleFileUpload { CustomerName = "Foo,Bar" },
new[] {
new UploadFile("upload1.png", stream1),
new UploadFile("upload2.png", stream2),
});
}
Or using only a Typed Request DTO. The JsonHttpClient also includes async equivalents for each of the new
PostFilesWithRequest APIs:
using (var stream1 = uploadFile1.OpenRead())
using (var stream2 = uploadFile2.OpenRead())
{
var client = new JsonHttpClient(baseUrl);
var response = await client.PostFilesWithRequestAsync<MultipleFileUploadResponse>(
new MultipleFileUpload { CustomerId = 123, CustomerName = "Foo,Bar" },
new[] {
new UploadFile("upload1.png", stream1),
new UploadFile("upload2.png", stream2),
});
}

Resources