Can you point me to a good and working examples of how to Consume Restful services in web ASP.net. Tutorials, walk-through or any useful material. I just join a company that require me to do that and I am new to ASP.net especially the rest service. I have used many materials and yet not clear.
Help me with the A B C of Rest usage in ASP.net pls
Here is a code that works with my Rest Servive.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Script.Serialization;
using Newtonsoft.Json;
using System.IO;
using System.Runtime.Serialization.Formatters;
using System.Net;
namespace WebTestRestfullService
{
public partial class _Default : Page
{
public string JS;
public string resp;
protected void Page_Load(object sender, EventArgs e)
{
}
public void Page_Init(object sender, EventArgs e)
{
using (var client = new HttpClient())
{
//client.BaseAddress = new Uri("http://88.208.232.99:0000");//Dont use this.
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("Application/json"));
//This is wrong too
//client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("Correct/api/"));
string query = "Correct/api/";//You must get the api refernce correct.
// HTTP GET
//HttpResponseMessage response = await client.GetAsync(". ");
string resp = "";
var task = client.GetAsync(query).ContinueWith
((taskwithresponse) =>
{
var response = taskwithresponse.Result;
var jsonstr = response.Content.ReadAsStringAsync();
jsonstr.Wait();
resp = jsonstr.Result;
});
task.Wait();
Response.Write(resp);
// string data = $.parseJSON(lbltest.Text);
// Session["resp"] = resp;
// new code
}
}
}
}
I have been working on a REST client library that works on all .NET based platforms.
https://bitbucket.org/MelbourneDeveloper/restclient-.net
There is a sample REST service there that calls another REST service. The service is written for ASP.NET Core so it should help you.
Related
So I am building a template API project and am currently working on adding in some integration tests.
At the moment, when I run my test, for some reason it returns a JSON parsing error:
Newtonsoft.Json.JsonReaderException : Unexpected character encountered
while parsing value: A. Path '', line 0, position 0.
This looks like it's an issue with my endpoint, but it works fine when just running localhost with a normal startup routine, so I think it's because I can't get my fixture just right. especilaly because, when i try another fixture (listed below) it doesn't give me an error anymore and just hangs.
The test itself can be found here.
namespace Foundation.Api.Tests.IntegrationTests
{
using FluentAssertions;
using Foundation.Api.Data;
using Foundation.Api.Models;
using Foundation.Api.Tests.Fakes;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Xunit;
public class GetValueToReplaceIntegrationTests : IClassFixture<CustomWebApplicationFactory<Startup>>
{
public GetValueToReplaceIntegrationTests(CustomWebApplicationFactory<Startup> factory)
{
_factory = factory;
}
private readonly CustomWebApplicationFactory<Startup> _factory;
[Fact]
public async Task GetValueToReplaces_ReturnsSuccessCodeAndResourceWithAccurateFields()
{
var fakeValueToReplaceOne = new FakeValueToReplace { }.Generate();
var fakeValueToReplaceTwo = new FakeValueToReplace { }.Generate();
var appFactory = _factory;
using (var scope = appFactory.Services.CreateScope())
{
var context = scope.ServiceProvider.GetRequiredService<ValueToReplaceDbContext>();
context.Database.EnsureCreated();
context.ValueToReplaces.RemoveRange(context.ValueToReplaces);
context.ValueToReplaces.AddRange(fakeValueToReplaceOne, fakeValueToReplaceTwo);
context.SaveChanges();
}
var client = appFactory.CreateClient(new WebApplicationFactoryClientOptions
{
AllowAutoRedirect = false
});
var result = await client.GetAsync($"api/v1/ValueToReplaceLowers")
.ConfigureAwait(false);
var responseContent = await result.Content.ReadAsStringAsync()
.ConfigureAwait(false);
var response = JsonConvert.DeserializeObject<IEnumerable<ValueToReplaceDto>>(responseContent);
// Assert
result.StatusCode.Should().Be(200);
response.Should().ContainEquivalentOf(fakeValueToReplaceOne);
response.Should().ContainEquivalentOf(fakeValueToReplaceTwo);
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
}
}
The fixture can be found here.
namespace Foundation.Api.Tests
{
using Foundation.Api.Data;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder
.ConfigureServices(services =>
{
// Remove the app's ValueToReplaceDbContext registration.
var descriptor = services.SingleOrDefault(
d => d.ServiceType ==
typeof(DbContextOptions<ValueToReplaceDbContext>));
if (descriptor != null)
{
services.Remove(descriptor);
}
// Add ValueToReplaceDbContext using an in-memory database for testing.
services.AddDbContext<ValueToReplaceDbContext>(options =>
{
options.UseInMemoryDatabase("TestingDb");
});
// Build the service provider.
var sp = services.BuildServiceProvider();
// Create a scope to obtain a reference to the database
// context (ValueToReplaceDbContext).
using (var scope = sp.CreateScope())
{
var scopedServices = scope.ServiceProvider;
var db = scopedServices.GetRequiredService<ValueToReplaceDbContext>();
// Ensure the database is created.
db.Database.EnsureCreated();
try
{
db.RemoveRange(db.ValueToReplaces);
// Seed the database with test data.
//Utilities.InitializeDbForTests(db);
}
catch (Exception ex)
{
}
}
});
}
}
}
I've also tried a fixture like so inspired by this one which just times out.
namespace Foundation.Api.Tests
{
using Foundation.Api.Data;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder
.ConfigureServices(services =>
{
// Create a new service provider.
var serviceProvider = new ServiceCollection()
.AddEntityFrameworkInMemoryDatabase()
.BuildServiceProvider();
// Add a database context using an in-memory
// database for testing.
services.AddDbContext<ValueToReplaceDbContext>(options =>
{
options.UseInMemoryDatabase("InMemoryDbForTesting");
options.UseInternalServiceProvider(serviceProvider);
});
services.AddScoped(provider => provider.GetService<ValueToReplaceDbContext>());
var sp = services.BuildServiceProvider();
// Create a scope to obtain a reference to the database
using var scope = sp.CreateScope();
var scopedServices = scope.ServiceProvider;
var context = scopedServices.GetRequiredService<ValueToReplaceDbContext>();
// Ensure the database is created.
context.Database.EnsureCreated();
try
{
// Seed the database with test data.
//Utilities.InitializeDbForTests(context);
}
catch (Exception ex)
{
//logger.LogError(ex, "An error occurred seeding the " +
// $"database with test messages. Error: {ex.Message}");
}
})
.UseEnvironment("Test");
}
}
}
The repo can be found here.
i've been trying for days to implement a simple server on HoloLens to receive HTTP packets sent from a smart object on a local network.
My code so far is the following (i report only the part of the code that actually runs on HoloLens):`
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using UnityEngine.Networking;
using System.Net.Sockets;
using System.Net;
using System.Threading;
using System.Text;
using UnityEngine.UI;
#if !UNITY_EDITOR
using Windows.Networking;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
using Windows.Networking.Connectivity;
#endif
public class DolphinManager : MonoBehaviour
{
private static string holoLensIpAddr = "192.168.0.147";
private static int holoLensPort = 12345;
#if UNITY_EDITOR
private HttpListener _listener;
#endif
#if !UNITY_EDITOR
private StreamReader reader;
private StreamSocketListener listener;
#endif
void Start()
{
#if UNITY_EDITOR
Invoke("InitializeUnityServer", 4f);
#else
Invoke("InitializeUWPServer", 4f);
#endif
}
#if !UNITY_EDITOR
private async void InitializeUWPServer()
{
try
{
listener = new StreamSocketListener();
serverHost = new Windows.Networking.HostName(anyIp);
listener.ConnectionReceived += Listener_ConnectionReceived;
listener.Control.KeepAlive = false;
await listener.BindServiceNameAsync(holoLensPort.ToString());
} catch(Exception e) { Debug.Log(e.Message); }
}
#endif
#if !UNITY_EDITOR
private async void Listener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
Debug.log("message received!");
}
The server starts correctly, but when i try to send a packet from my smart object, Listener_ConnectionReceived() is not triggered.
I have already set the PrivateNetworkClientServer capability on the app manifest.
What could be wrong?
Thank you in advance!
I am migrating an ASP.NET Web API application to OWIN. That is not intended to use none OWIN deployments. So Global.asax is going to be removed. There are some code put into Global.asax event handlers specially in Application_EndRequest that should be handled by OWIN.
I have read some article about OWIN and searched the internet but couldn't determine how it can be done. Can anyone please describe how it can be done?
My environment:
Visual Studio 2015 RC
.Net Framework 4.5
Microsoft.AspNet.Cors.5.0.0
Microsoft.AspNet.WebApi.5.2.3
Microsoft.Owin.3.0.1
Owin.1.0
UPDATE: Here it is some sections of current code
using System;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using ProjectX.Web.AppStart;
using ProjectY.Domain.Contracts;
namespace ProjectX.UI
{
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_EndRequest(object sender, EventArgs e)
{
var unitOfWork = DependencyResolver.Current.GetService(typeof(IUnitOfWork)) as IUnitOfWork;
unitOfWork.SaveChanges();
}
}
}
namespace ProjectY.Domain.Contracts
{
public interface IUnitOfWork
{
void SaveChanges();
IRepository<T> GetRepository<T>() where T : class, IEntity, IHistory;
IDbContext GetDbContext();
}
}
using ProjectY.Core.Repositories;
using ProjectY.Domain.Contracts;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ProjectY.Core.UnitOfWork
{
public class UnitOfWork : IUnitOfWork
{
public UnitOfWork(IProjectYDbContextFactory contextFactory)
{
_context = contextFactory.GetContext();
}
public void SaveChanges()
{
if (_context == null)
throw new ApplicationException("Something wrong has been happened. _context must not be null.");
_context.SaveChanges();
}
}
}
I stumbled upon this question while updating some legacy applications. For those still seeking the answer: you can solve this by creating a middleware:
app.Use(async (context, next) =>
{
await next.Invoke().ConfigureAwait(false);
//Do stuff after request here!
var unitOfWork = DependencyResolver.Current.GetService(typeof(IUnitOfWork)) as IUnitOfWork;
unitOfWork.SaveChanges();
});
You can use stage markers if you need more control on when your middleware will be called in the request processing pipeline.
See also https://learn.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/owin-middleware-in-the-iis-integrated-pipeline#stage-markers
Hello guys im trying to save a picture taken from my webcam.
im actually using this code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
public partial class ImageConversions : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CreatePhoto();
}
void CreatePhoto()
{
try
{
string strPhoto = Request.Form["imageData"]; //Get the image from flash file
byte[] photo = Convert.FromBase64String(strPhoto);
FileStream fs = new FileStream("C:\\Webcam.jpg", FileMode.OpenOrCreate, FileAccess.Write);
BinaryWriter br = new BinaryWriter(fs);
br.Write(photo);
br.Flush();
br.Close();
fs.Close();
}
catch (Exception Ex)
{
}
}
}
The application RUNS, i get to see the image , i click the capture button it gives no error till here BUT BUT BUT ... NO IMAGE IS SAVED EITHER i downloaded the sample from
HERE : http://www.dotnetspider.com/resources/38150-Capture-save-images-from-Web-camera.aspx (check the attachemnt)
Change Path.. I also had same problem..
Your C Drive Has security level high,
Change path to "D:\Webcam.jpg" and it will work
Try this article. It works pretty good. But I couldn't work with a custom message when webcam is not attached. It gives a auto generated error message.
webcamlibrarydotnet
I have an ASP.net project which involves using a custom IHttpModule. This module will sit in the pipeline and when certain criteria match up, it should invoke a method on a WCF service hosted in a simple C# console application on the same machine.
The code for the module is below:
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.SessionState;
using System.Web;
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Configuration;
using System.ServiceModel;
using SimpleFarmStateServer;
namespace SimpleFarm
{
public class SimpleFarmModuleSS : IHttpModule, IRequiresSessionState
{
protected string cache_directory = "";
// WCF
ChannelFactory<IStateServer> factory;
IStateServer channel;
public void Dispose() { }
public void Init(System.Web.HttpApplication context)
{
context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
setupFactory();
}
void setupFactory()
{
factory = new ChannelFactory<IStateServer>(
new NetNamedPipeBinding(),
"net.pipe://localhost/StateServer");
}
void context_PreRequestHandlerExecute(object sender, EventArgs e)
{
try
{
if (factory.State != CommunicationState.Opened)
setupFactory();
channel = factory.CreateChannel();
channel.LogAccess("Hello World!");
}
catch (Exception ex)
{
}
finally
{
factory.Close();
}
}
}
}
My problem is that this runs the first time, but then subsequent attempts cause this error message
The communication object,
System.ServiceModel.Channels.ServiceChannel,
cannot be used for communication
because it is in the Faulted state.
It seems as if I am doing something wrong, and I am new to WCF in general so this is very likely.
I think the issue is surrounding the ChannelFactory being recreated, and this causes the faulted state.
The specific error probably means the factory faulted, threw an exception (which you're swallowing) and then when the finally block executes, the factory.Close() call fails because the factory is faulted (if a WCF object is faulted, you need to call Abort() on it, not Close()).