communicate with WEB Api from windows phone project - c#

Ive got Web API project which hosts data service. Everything is ok and I can consume it from console client using this code:
private static async Task RunAsync()
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:15017/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// HTTP GET
HttpResponseMessage response = await client.GetAsync("api/products");
if (response.IsSuccessStatusCode)
{
var products = await response.Content.ReadAsAsync<List<Product>>();
foreach (var product in products)
{
Console.WriteLine(product.Name);
Console.WriteLine(product.Description);
Console.WriteLine(product.ShortDescription);
Console.WriteLine(product.Prize);
Console.WriteLine("\n");
}
}
}
}
private static void Main(string[] args)
{
RunAsync().Wait();
}
Works perfect.
Than I have windows phone 8 app. It has such a structure that I have ViewModels which create instances of IRepository interfaces. I try to connect to web api and load data from IRepository classes using the same code as in my console app but when I try to add reference to System.Net.Http.Formatting which is needed Ive got an error whiole installing package:
Adding 'Microsoft.AspNet.WebApi.WebHost 5.1.2' to PhoneApp.
Install-Package : Could not install package 'Microsoft.AspNet.WebApi.WebHost 5.1.2'. You are trying to install this package into a project that
targets 'WindowsPhone,Version=v8.0', but the package does not contain any assembly references or content files that are compatible with that
framework. For more information, contact the package author.
So how can I consume web api from inside my windows phone app ?

Related

Read local/static file in Blazor Wasm

My project is created in Blazor WASM ( I do not want to use Blazor server )
I would like to read XSD files from wwwroot:
Inside my XsdService.cs - c# class I was trying:
string pathToXsd = Path.Combine("plcda","extPL_r2.xsd");
string transformataHTML = System.IO.File.ReadAllText(pathToXsd);
However, I always get errors:
Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
Unhandled exception rendering component: Could not find a part of the path "/plcda/extPL_r2.xsd".
System.IO.DirectoryNotFoundException: Could not find a part of the path "/plcda/extPL_r2.xsd".
So is there any chance to include custom/static/local files to Blazor WASM? And read them even if app is offline?
Create a Http GET call to the files. Think of Blazor wasm as a SPA application. All of the files that are required to run your app are downloaded into a users browser. Everything else like images are fetched on request. Like an images is requested by the browser.
#inject HttpClient _client
#code {
async Task GetXDSFile()
{
var byteOfTheFile = await _client.GetByteArrayAsync("plcda/extPL_r2.xsd");
}
}
This sample just fetches the file as byte array. Other version of the Get maybe more sutaible for you like GetStreamAsync.
In .NET Core 6 you can add provider mappings to your client project's program.cs to serve static files.
For example I need to load a 3d model (.obj, .mtl files):
Blazor WASM Client Only Project:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.StaticFiles;
var provider = new FileExtensionContentTypeProvider();
provider.Mappings.Add(".obj", "application/obj");
provider.Mappings.Add(".mtl", "application/mtl");
builder.Services.Configure<StaticFileOptions>(options =>
{
options.ContentTypeProvider = provider;
});
await builder.Build().RunAsync();
If you have an asp.net core hosted project you can simply put this in the server project's program.cs file instead and you shouldn't need to add nuget package references.
Blazor WASM Asp.net Core Hosted Project:
using Microsoft.AspNetCore.StaticFiles;
var provider = new FileExtensionContentTypeProvider();
provider.Mappings.Add(".babylon", "application/javascript");
provider.Mappings.Add(".obj", "application/obj");
provider.Mappings.Add(".mtl", "application/mtl");
builder.Services.Configure<StaticFileOptions>(options =>
{
options.ContentTypeProvider = provider;
});
var app = builder.Build();

.NET Core 2.2 Receiving 401 Unauthorized response when calling IIS site on same server with Windows Auth

I'm having some strange behavior in my .NET Core 2.2 application.
When trying to make an HTTP request (through either HttpClient or RestSharp), as long as the site that I am requesting is hosted on a different server than where my calling application resides, I receive a 200 response, just like I'd expect, which is great.
However, as soon as I try to hit a site on the same server (and I've tried this with the exact same site hosted on both servers), I get a 401 Unauthorized.
For reference, the site that I am requesting is a ASP.NET Web API on .Net Framework, and it uses Windows Auth.
I've tried this in .Net Framework 4.6.2 and .Net Core 3.0, and both of them work fine, and do not exhibit this problem -- it seems just to affect 2.2 for me.
I know there is the "Loopback Check Issue", however if this was the case, I'd expect .Net Framework and .Net Core 3.0 to face the same problem.
I also am aware of This GitHub Issue however that seems to have been solved in 2.2.
For reference here is some sample code that demonstrates the problem with HttpClient (The same codes is used for all versions of .Net)
static async Task Main(string[] args)
{
await MakeRequest();
}
public async static Task MakeRequest()
{
Console.WriteLine("Enter URL:");
var url = Console.ReadLine();
var uri = new Uri(url);
try
{
var client = new HttpClient(new HttpClientHandler { UseDefaultCredentials = true });
var res = await client.GetAsync(uri);
res.EnsureSuccessStatusCode();
var content = await res.Content.ReadAsStringAsync();
Console.WriteLine(res.StatusCode);
Console.WriteLine(content);
}
catch (Exception e)
{
Console.WriteLine($"Error: {e}");
}
finally
{
await MakeRequest();
}
}
Any ideas?
EDIT:
SDK used: 2.2.104
Runtime used: 2.2.5
2.2.5 seems to be the version of .NET core runtime version instead of .NET CORE SDK version.
The latest version of 2.2 sdk is 2.2.4.
Since 2.2.7 would be the update verion of 2.2.5 and this issue is not happening in runtime 2.2.7. Is it acceptable to just update runtime 2.2.7 on your server?

ASP.Net Core API Accessing HttpRequestMessage

I have a ASP.Net 4.5 application that I am trying to upgrade to ASP.Net Core. This application receives calls from a 3rd party application.
In my old application I have an action that looks like this:
public async Task<HttpResponseMessage> RealTimeAsync(HttpRequestMessage request)
{
var StatusMessage = string.Empty;
try
{
var doc = new XmlDocument();
doc.Load(await request.Content.ReadAsStreamAsync());
From 4.5 this works fine. However, when I use this code in ASP.Net core I get an "Object Reference Not Set to an Instance of an Object" error because request.Content is null.
The requests coming in to the two applications (4.5 and .Net Core) are the same. Why is request.Content null in my .Net Core application?
When I referenced this post: ASP.NET Core HTTPRequestMessage returns strange JSON message
I tried installing the suggested Nuget Package. However, it is not compatible with .Net Core:
error: Package Microsoft.AspNet.WebApi.Client 5.2.2 is not compatible
with netcoreapp1.0 (.NETCoreApp,Version=v1.0). Package
Microsoft.AspNet.WebApi.Client 5.2.2 supports: error: - net45
(.NETFramework,Version=v4.5) error: -
portable-net45+netcore45+wp8+wp81+wpa81
(.NETPortable,Version=v0.0,Profile=wp8+netcore45+net45+wp81+‌​wpa81)
error: One or more packages are incompatible with
.NETCoreApp,Version=v1.0.
That code needs to be refactored to use more recent structure.
public Task<IActionResult> RealTimeAsync() {
var StatusMessage = string.Empty;
try {
var request = this.Request;
var doc = new XmlDocument();
doc.Load(request.Body); //request.Body returns a stream
//...other code...

Xamarin needs reference to Windows.Foundation.FoundationContract

I have created a new iPhone (iOs 9.3) app with Xamarin from within Visual Studio 2015 update 2. I have Xamarin beta channel on the mac (which has Xcode etc.)
I have this code:
using Windows.Web.Http;
...
private async void GetPois()
{
var client = new HttpClient();
var response = await client.GetAsync(new Uri("http://onlinesource/json"));
}
and I get the error on the GetAsync I do not have the httpclient nuget installed, because it threw an error.
already had ModernHttpClient nuget installed, but did not use it. #Andrii Krupka yes I also have using System;
I added System.Net.Http instead of Windows but now I have type or namespace could not be found. added a reference to both system.net and system.net.http and now it works. next thing to solve is to disable ats. will mark this as answered by #SushiHangover thanks everyone!
Use the namespace System.Net.Http instead of Windows.....
Then your HttpClient will work fine under iOS, assuming your have disable ATS since that is a non-secure HTTP link... ;-)
var client = new HttpClient();
var response = await client.GetAsync(new Uri("http://onlinesource/json"));
On a personal note: I greatly prefer ModernHttpClient #
https://github.com/paulcbetts/modernhttpclient
(Cross platform, PCL, cleaner, faster, able to leap buildings in a single request, etc...)

Is it possible to use owin to self host WebApi in visual studio 2010 / Framework 4

I am trying to to run a self hosted web api app using owin like here
http://www.asp.net/web-api/overview/hosting-aspnet-web-api/use-owin-to-self-host-web-api
public class Program
{
static void Main()
{
string baseAddress = "http://localhost:9000/";
// Start OWIN host
using (WebApp.Start<Startup>(url: baseAddress))
{
Console.WriteLine("App started");
Console.ReadLine();
}
}
}
public class Startup
{
// This code configures Web API. The Startup class is specified as a type
// parameter in the WebApp.Start method.
public void Configuration(IAppBuilder appBuilder)
{
// Configure Web API for self-host.
HttpConfiguration config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
appBuilder.UseWebApi(config);
}
}
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
which event.
I tried to install Microsoft.AspNet.WebApi (Web Api 2.1) via nuget which fails because of framework 4.5 requirement so I installed AspNetWebApi (Web Api).
But I can't find the extension method UseWebApi anywhere. Do I have to install another package or is it impossible to host a web api with Framework 4?
I don't think that you can use OWIN, bute you can create a self-hosted web api using Visual Studio 2010 and .NET Framework 4.0 using this approach:
http://www.asp.net/web-api/overview/older-versions/self-host-a-web-api
While the approach is not recommended for new designs, I'm forced to use .NET Framework 4.0 due to dependencies in our existing code base. The article is written with Visual Studio 2012 but I've just tested the server side with Visual Studio 2010 and it appears to work ok. I used Postman instead of the client example.
Probably not because the self hosting package depends on System.Web.Http.Owin, which was built in .Net 4.5 . Unless, you are ready to rewrite the hosting stuff using Microsoft source code at https://katanaproject.codeplex.com/SourceControl/latest#README

Categories

Resources