RESTful framework alternatives to WCF - wcf

Looking for alternatives to the WCF REST start kit, ideally OSS frameworks.
Anyone got a list?
Cheers
Ollie

OpenRASTA is the most mature

ASP.NET MVC is a good alternative when it comes to generating REST XML and JSON feeds.

To build a rest architecture in .net you can use GenericHandlers. You can create a GenericHandler that will receive a HTTP message (POST, GET or..) and return a message of the content-type you specify.
For example I create a generic handler on the url:
http://site/getpeople.ashx?gender=female
And call it with the parmeter gender=female, as above the handler will return the following
<people>
<person>...</person>
...
<people>
And the content type would be text/xml.
This is the simplest way to implement REST web services in .NET

I also provide ServiceStack, a modern, code-first, DTO-driven, WCF replacement web services framework encouraging code and remote best-practices for creating DRY, high-perfomance, scalable REST web services.
There's no XML config, or code-gen and your one clean C# web service is enabled on all JSON, XML, SOAP, JSV, CSV, HTML endpoints out-of-the-box, automatically. It includes generic sync/async service clients providing a fast, typed, client/server communication gateway end-to-end.
It also includes generic sync/async service clients providing a fast, typed, client/server communication gateway end-to-end.
This is the complete example of all the code needed to create a simple web service, that is automatically without any config, registered and made available on all the web data formats on pre-defined and custom REST-ful routes:
public class Hello {
public string Name { get; set; }
}
public class HelloResponse {
public string Result { get; set; }
}
public class HelloService : IService<Hello> {
public object Execute(Hello request) {
return new HelloResponse { Result = "Hello, " + request.Name };
}
}
Above service can be called (without any build-steps/code-gen) in C# with the line below:
var response = client.Send<HelloResponse>(new Hello { Name = "World!" });
Console.WriteLine(response.Result); // => Hello, World
And in jQuery with:
$.getJSON('hello/World!', function(r){
alert(r.Result);
});

Related

How to start on ServiceStack?

Can you help me point out how should I start on this:
I'm new to API , and I'm currently working on ASP.NET Core 3.1 MVC paired with Microsoft SQL Server. I have requirement that I should use API (ServiceStack) for a certain method.
My question are :
how or where do I start from my existing project solution?
If I use API should it be calling on SQL also? (I supposed the data will stay on db)
with regards to first question : they gave me a link where I can see this.
Where should I start , I'm just so confused.
I've looked up on youtube but there's no similar case to mine, they all use in-memory.
Suggestions and advice are welcome !
Go through ServiceStack's Getting Started Section starting with Create your first Web Service.
Configure OrmLite in your AppHost
To configure OrmLite, start with the OrmLite Installation tells you which package to download whilst the OrmLite Getting Started docs lists all the available SQL Server Dialects which you'd use to configure the OrmLiteConnectionFactory in your IOC.
E.g. for SQL Server 2012:
public class AppHost : AppHostBase
{
public AppHost() : base("MyApp", typeof(MyServices).Assembly) { }
// Configure your ServiceStack AppHost and App dependencies
public override void Configure(Container container)
{
container.AddSingleton<IDbConnectionFactory>(
new OrmLiteConnectionFactory(connectionString,
SqlServer2012Dialect.Provider));
}
}
Using OrmLite in Services
Then inside your ServiceStack Services you can access your ADO .NET DB connection via base.Db which you can use with OrmLite's extension methods, e.g:
public class MyServices : Service
{
public object Any(GetAllItems request) => new GetAllItemsResponse {
Results = Db.Select<Item>()
};
}
Checkout the OrmLite APIs docs for different APIs to Select, Insert, Update & Delete Data.
Creating effortless RDBMS APIs using AutoQuery
As you're new I'd highly recommend using AutoQuery RDBMS since it lets you create RDBMS APIs with just Request DTOs.
You can enable it by adding the AutoQueryFeature plugin in the ServiceStack.Server" NuGet package:
public override void Configure(Container container)
{
Plugins.Add(new AutoQueryFeature { MaxLimit = 100 });
}
Then you can create an AutoQuery API for your Item table with just:
[Route("/items")]
public class QueryItems : QueryDb<Item> {}
Which will now let you query each Item column using any of AutoQuery's implicit conventions, e.g by exact match:
/items?Id=1
Or by any of the query properties:
/items?NameStartsWith=foo
Creating Typed Request DTO
Once you know which Query APIs your client Apps needs I'd recommend formalizing them by adding them as strong typed properties in your Request DTO, e.g:
[Route("/items")]
public class QueryItems : QueryDb<Item>
{
public int? Id { get; set; }
public string NameStartsWith { get; set; }
}
Calling from Service Clients
Which will enable an end-to-end Typed API using any of ServiceStack's Service Clients, e.g:
var client = new JsonServiceClient(BaseUrl);
var response = client.Get(new QueryItems { NameStartsWith = "foo" });
response.PrintDump(); // quickly view results in Console
There's also AutoQuery CRUD APIs that will let you create APIs that modify your RDBMS tables using just Request DTOs.

Can't use Json() in asp.net core web api as it in asp.net core web

In asp.net core web I create a controller and I can use:
return Json(new {status=true});
but in asp.net core web API I can't do it.
In a controller:
[HttpGet("{id}")]
public JsonResult Get(int id)
{
}
I can not return Json()
How to use it?
Asp.Net Core Web API does provide support for wide varieties of response types, with Json being one among them. You can do that like shown below. Make sure you have all your required dependencies. You can learn about the dependencies from the documentation link I attached in this answer.
[HttpGet]
public IActionResult Get()
{
return Json(model);
}
You can also specify strict response formats using the [Produces] Filter on your controller.
Configuring Custom Formatters
You can also configure your own custom formatters in Asp.Net Web API project by calling the .AddFormatterMappings() from ConfigureServices method inside of your Startup.cs. This allows for a greater control on your content negotiation part and lets you achieve strict restrictions.
Please go through this documentation to understand further.
Using Responses with Status Codes
However, when using Web API, I suggest you use the helper methods that are built in so that your response becomes more expressive as it contains both the response content along with the status code. An example of how to do that is below
[HttpGet]
public ActionResult Get()
{
return Ok(_authors.List());
}
For a full list of helper methods available, you can take a look at the Controller.cs and ControllerBase.cs classes.
Asp.net core web api inherit from controllerBase, which doesn't contain a Json(Object) method. You should initialize a new JsonResult yourself in the action.
[HttpGet("{id}")]
public JsonResult Get(int id)
{
return new JsonResult(new { status = true });
}

Can I add a service info / health check endpoint to my Identity Server 3-based service?

I have a set of AspNet WebApi-based web services and an IdentityServer3-based authentication service. All of the web services support a simple service info endpoint that we use for monitoring and diagnosis. It reports the service version and the server name. The only service that currently does not support the service info endpoint is the IdentityServer3-based authentication service.
Is there a way to add a simple endpoint to an IdentityServer3-based service? In GitHub issue 812 Brock Allen says "We have a way to add custom controllers, but it's undocumented, current unsupported, and not really done." I'd rather not take that indocumented, unsupported route.
Is there a way to modify/extend the discovery endpoint to include additional information?
Here's how I ended up coding this up. At a high level, basically I added a Controllers folder, created a AuthenticationServiceInfoController class with a single GET action method and then registered that controller during Startup. As noted in comment above, my solution had some extra complexity because my AuthenticationServiceInfoController inherited from a base ServiceInfoController defined elsewhere, but I've tried to eliminate that from this sample. So, the controller code looks like this:
[RoutePrefix("api/v1/serviceinfo")]
public class AuthencticationServiceInfoController : IServiceInfoController
{
[Route("")]
[Route("~/api/serviceinfo")]
public IHttpActionResult Get()
{
try
{
ServiceInformation serviceInfo = new ServiceInformation();
serviceInfo.ServiceVersion = Global.serviceVersion;
return Ok(serviceInfo);
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
}
It implements a simple interface:
public interface IServiceInfoController
{
IHttpActionResult Get();
}
And in my Startup.Configuration method where I configure Identity Server, I've got:
var idSrvFactory = new IdentityServerServiceFactory();
idSrvFactory.Register(new Registration<IServiceInfoController, Controllers.AuthencticationServiceInfoController>());
I think that's all that it took. It's in place and working in my Identity Server 3-based service.

How should I consume a WCF service using MVC3

I am writing a fairly simple MVC3 application that allows a user to retrieve and modify some configuration data held by a WCF service. The configuration data will not change very often but needs to be maintainable by the user.
Once the user is happy with the configuration, they will launch some processing from the UI or by the scheduled execution of a VB script.
I'm fairly new to WCF and even newer to MVC3 but I'd like to make all the comms to and from the service RESTful. Is this a good thing to do?
I'd been planning to perform the service communications from the MVC controller. This would make a HTTP Get request to retrieve the current configuration and a HTTP Post to apply the modified configuration. I'd also use a Get request to launch the processing.
Could anyone provide an example (or point me in the direction) of how I should be doing this?
Please follow the below links for some sample code to build a RESTful WCF Service and the how the client would access the service.
Link to create a RESTful service: here
Link to create a .NET client that consumes the RESTful service : here
Hope the information helps you out.
If you are the owner of web service, you can directly reference implementation of service in your mvc project and use it without web reference. You can write some like this:
// example of ws
public class Service1 : IService1
{
public string GetData( int value )
{
return string.Format( "You entered: {0}", value );
}
public CompositeType GetDataUsingDataContract( CompositeType composite )
{
if( composite == null )
{
throw new ArgumentNullException( "composite" );
}
if( composite.BoolValue )
{
composite.StringValue += "Suffix";
}
return composite;
}
}
// example of mvc action
public class HomeController : Controller
{
public ActionResult Index()
{
IService1 service = new Service1();
service.GetDataUsingDataContract(....)
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
}
The simplest answer I've found was here:, using the channel factory.
I still don't know if it's the best way but it left my code looking clean enough. Below is a sample from my controller.
public ActionResult Index()
{
SettingsModel config = null;
// Set up a channel factory to use the webHTTPBinding
using (WebChannelFactory<IChangeService> serviceChannel =
new WebChannelFactory<IChangeService>(new Uri(baseServiceUrl )))
{
IChangeService channel = serviceChannel.CreateChannel();
config = channel.GetSysConfig();
}
ViewBag.Message = "Service Configuration";
return View(config);
}

RhinoMock help: Mocking WCF service

I'm trying to use RhinoMock for mocking out a wcf service.
Say I have the following service:
[OperationContract]
List<User> SearchUsers(UserSearchFilter filter);
Adding this service with Visual Studio will generate a proxy, and that proxy has a Interface like:
public interface ResourceService {
System.IAsyncResult BeginSearchUsers(UserSearchFilter filter, System.AsyncCallback callback, object asyncState);
ObservableCollection<User> EndSearchUsers(System.IAsyncResult result);
}
Then I create a ViewModel that uses this service, like this:
private ResourceService service;
public ViewModelBase(ResourceService serv)
{
service = serv;
var filter = new UserSearchFilter();
service.BeginSearchUsers(filter, a =>
{
this.Users = service.EndSearchUsers(a);
}, null);
}
Then comes the question. How do I mock this service using RhinoMock?
[TestMethod]
public void UserGetsPopulatedOnCreationOfViewModel()
{
// Is stub the right thing to use?
ResourceService serv = MockRepository.GenerateStub<ResourceService>();
// Do some setup... Don't know how?
var vm = new ViewModel(serv);
Assert.IsTrue(vm.Users.Count > 0);
}
I be really happy if someone could help me with the correct usage of RhinoMock
(Note: I'm using Silverlight, but I don't think that would change the way RhinoMock is used)
Thanks a lot!
I wrote a 4-part article all about testing apps that use WCF services.
Part 2 talks about mocking out the service using RhinoMocks
Part 3 talks about mocking out an asynchronous service using Moq
Note that part 3 can be translated over to RhinoMocks very easily. I was just trying to show different mocking frameworks, and that the technique did not rely on the mocking framework.
Hope it helps!
EDIT
So, in Rhino Mocks, you do this in the setup:
mockService.YourEvent += null;
IEventRaiser loadRaiser = LastCall.IgnoreArguments().GetEventRaiser();
Then in the playback, you do this:
loadRaiser.Raise(mockService, CreateEventArgs());
You can find more info on mocking events in Rhino in Phil Haack's blog post.
I would create interface that service would implement (IResourceService).
Then on Silverlight side create custom implementation of IResourceService that calls WCF service itself.
RihnoMock would create the stub for IResourceService interface and not for WCF service.
It's very easy to do using Prism 2, you can read more here:
http://mokosh.co.uk/post/2009/04/19/prism-2-wpf-and-silverlight-services/