Where can I specify custom serialization/deserialization in an ASP.NET Web API?
The throughput of our application requires a fast serialization/deserialization of messages, hence we need to tightly control this part of the code to either use our home-brew or an OSS one out there.
I have checked various sources such as this that explains how to create a custom value provider, but I have yet to see an example that explains the process end to end.
Can anyone direct/show me the way to serialize the incoming/outgoing messages?
Also a diagram of the various injection points/event sinks in Web API similar to this one for WCF is appreciated!
The extension point you're looking for is the MediaTypeFormatter. It controls reading from the request body and writing to the response body. This might be the best resource for writing your own formatter:
http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters
Here's code example in case link in the answer above dies
public class MerlinStringMediaTypeFormatter : MediaTypeFormatter
{
public MerlinStringMediaTypeFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/plain"));
}
public override bool CanReadType(Type type)
{
return type == typeof (YourObject); //can it deserialize
}
public override bool CanWriteType(Type type)
{
return type == typeof (YourObject); //can it serialize
}
public override Task<object> ReadFromStreamAsync(
Type type,
Stream readStream,
HttpContent content,
IFormatterLogger formatterLogger)
{
//Here you put deserialization mechanism
return Task<object>.Factory.StartNew(() => content.ReadAsStringAsync().Result);
}
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
{
//Here you would put serialization mechanism
return base.WriteToStreamAsync(type, value, writeStream, content, transportContext);
}
}
Then you need to register your formatter in Global.asax
protected void Application_Start()
{
config.Formatters.Add(new MerlinStringMediaTypeFormatter());
}
Hope this saves you some time.
Related
This is more of a design related question, and any help/pointers in the right direction is highly appreciated.
I am working on a ASP.NET Web API2 application, and have an Authorization filter and other Action filters. Within these filters, I need to access the Request object that comes as a part of the HttpPost request body.
I use the following code to read the request body content and deserialize into the desired object. It works fine.
//actionContext is HttpActionContext
var requestContent = actionContext.Request.Content.ReadAsStringAsync();
var request = JsonSerializer.GetObject<BaseOTARequestModel>(requestContent.Result);
To serve a particular request, I am deserializing the request content twice (I have 2 filters). Once the request reaches the controller action, it is deserialized again by the Web API framework. I feel guilty that every request is deserialized 3 times, and have a feeling there is a better way to handle this.
How can I avoid deserializing the request multiple times in a request?
I took this on as a challenge and came up with this solution. Here's a base filter attribute class:
public abstract class BaseOTARequestFilterAttribute : ActionFilterAttribute
{
private HttpActionContext _actionContext;
protected BaseOTARequestModel RequestModel
{
get
{
if (_actionContext.Request.Properties.ContainsKey("RequestModel"))
{
return _actionContext.Request.Properties["RequestModel"] as BaseOTARequestModel;
}
return null;
}
set
{
_actionContext.Request.Properties["RequestModel"] = value;
}
}
public override void OnActionExecuting(HttpActionContext actionContext)
{
_actionContext = actionContext;
if (RequestModel == null)
{
//actionContext is HttpActionContext
var requestContent = actionContext.Request.Content.ReadAsStringAsync();
RequestModel = JsonSerializer.GetObject<BaseOTARequestModel>(requestContent.Result);
}
}
}
This base class handles your deserialization and uses the Request.Properties collection to store it. (OK, I know a Web API is stateless but this state only exists during the execution of the request so fine imho.)
Your various attributes should all inherit this base class and can use the derialized object as follows:
public override void OnActionExecuting(HttpActionContext actionContext)
{
base.OnActionExecuting(actionContext);
var data = RequestModel;
// etc.
}
This may not be the most elegant solution, but I believe it works. Interested to hear the views of others.
The title more or less says it all.
I am trying to configure the JSON MediaTypeFormatter to behave differently per route.
Specifically I have two routes in my WebAPI that are mapped to the same controller.
Each route performs the same operation and returns the same data but for reasons of backwards comparability with existing consumers they must format their output slightly differently.
I could put some code in the Controller to determine if the request came in on the legacy route or the new route and change the formatters accordingly.
I could also use an ActionFilter to change the formatters where required.
I was however wondering if there is a way to configure formatters at a per route level because that is the level of abstraction where my API behaves differently. This could either be at the point of Route Configuration or in a Delegate Handler.
Any suggestions?
I'm not entirely sure how much different your two JSONs are and what exactly you are doing with them, but if you ask me, I'd do it in the formatter:
public class MyJsonMediaTypeFormatter : JsonMediaTypeFormatter
{
private IHttpRouteData _route;
public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, System.Net.Http.Headers.MediaTypeHeaderValue mediaType)
{
_route = request.GetRouteData();
return base.GetPerRequestFormatterInstance(type, request, mediaType);
}
public override System.Threading.Tasks.Task WriteToStreamAsync(Type type, object value, System.IO.Stream writeStream, HttpContent content, TransportContext transportContext)
{
if (_route.Route.RouteTemplate.Contains("legacy"))
{
//here set the SerializerSettings for non standard JSON
//I just added NullValueHandling as an example
this.SerializerSettings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
};
}
return base.WriteToStreamAsync(type, value, writeStream, content, transportContext);
}
}
You would then replace the default JsonMEdiaTypeFormatter with this one.
config.Formatters.RemoveAt(0);
config.Formatters.Insert(0, new MyJsonMediaTypeFormatter());
In Web API you can have DelegatingHandler that only runs on a specific route, but that doesn't really make sense since Formatters collection is global so there is no point in modifying that in runtime even from a route-scoped handler.
I'm pretty new to MVVM light world, and after searches I can't find what I want to do.
My WP7 application contains a pivot, each pivot item content is View1 and viewmodel is VM1.
When loading my application, I'd like to create every pivot item with the same view and view model but with different parameter.
example :
PivotItem 1 -> send param "car" to the view model
PivotItem 2 -> send param "truck" to the view model, etc.
Google told me to use messaging but if I send 2 messages from my MainViewModel, both PivotItem1 and PivotItem2 ViewModel will receive these messages.
Am I wrong with this approach ?
Is there another solution to succeed ?
Thank you in advance for your answer.
PS : be indulgent, english is not my native language, don't hesitate to ask for further information.
Regards,
Aymeric Lagier
To seperate the messages use the second constructor signature whereby you can pass a token. This token can be anything but I generally use an enum to store all my message types within the system.
Create a static class in a common library and reference this in all projects where you need to send or receive messages.
The following code hopefully shows this approach, notice I am sending a string as a value within the message but this can be anything, even a complex object such as one of your business objects.
namespace MyProject.Common
{
public static class AppMessages
{
enum MessageTypes
{
ViewmodelA,
ViewmodelB
}
public static class ViewModelAUpdate
{
public static void Send(string value)
{
Messenger.Default.Send(value, MessageTypes.ViewmodelA);
}
public static void Register(object recipient, Action<string> action)
{
Messenger.Default.Register(recipient, MessageTypes.ViewmodelA, action);
}
}
public static class ViewModelBUpdate
{
public static void Send(string value)
{
Messenger.Default.Send(value, MessageTypes.ViewmodelB);
}
public static void Register(object recipient, Action<string> action)
{
Messenger.Default.Register(recipient, MessageTypes.ViewmodelB, action);
}
}
}
}
How about using a method to set the message you want to receive. (this could be done as a parameter in the constructor or a property as well)
public void RegisterForAppMessage(AppMessages.MessageTypes messageType)
{
switch (messageType)
{
case AppMessages.MessageTypes.PivotViewItem1Message:
AppMessages.PivotViewItem1Message.Register(this,DoSomethingWhenIRecievePivotViewItem1Messages)
break;
case AppMessages.MessageTypes.PivotViewItem2Message:
AppMessages.PivotViewItem2Message.Register(this,DoSomethingWhenIRecievePivotViewItem2Messages)
break;
}
}
private void DoSomethingWhenIRecievePivotViewItem2Messages(string obj)
{
// TODO: Implement this method
throw new NotImplementedException();
}
private void DoSomethingWhenIRecievePivotViewItem1Messages(string obj)
{
// TODO: Implement this method
throw new NotImplementedException();
}
Messaging sounds a bit heavy for this purpose. Could you simply inject a parameter into your ViewModel. If you already have MVVMLight you also have support for SimpleIOC. Maybe let the view locate its ViewModel when the view is resolved and there decide which parameter to use on the view model?
You can see an example of it here
I'm just getting started with ServiceStack and, as a test case, I am looking to rework an existing service which is built using standard ASP.Net handlers. I've managed to get it all working as I want it but have certain aspects which make use of the ASP.Net Session object.
I've tried adding IRequiresSessionState into the service interface:
public class SessionTestService : RestServiceBase<SessionTest>, IRequiresSessionState {
public override object OnPost(SessionTest request) {
// Here I want to use System.Web.HttpContext.Current.Session
}
}
The trouble is I can't seem to get it to work as the Session object is always null.
I've done a lot of Googling and have puzzled over https://github.com/mythz/ServiceStack/blob/master/tests/ServiceStack.WebHost.IntegrationTests/Services/Secure.cs and similar but I can't find any example code which does this (which surprises me). Can anyone explain why the above doesn't work and advise what I need to do to get it working?
Note: Ultimately I'll probably look to replace this with Redis or will try to remove any serverside session requirement, but I figured that I'd use the ASP.Net implementation for the time being, to get things working and to avoid reworking it more than is necessary at this point.
Using ServiceStack ISession
ServiceStack has a new ISession interface backed by ICacheClient that lets you share same ISession between MVC Controllers, ASP.NET base pages and ServiceStack's Web Services which share the same Cookie Id allowing you to freely share data between these web frameworks.
Note: ISession is a clean implementation that completely by-passes the existing ASP.NET session with ServiceStack's own components as described in ServiceStack's MVC PowerPack and explained in detail in the Sessions wiki page.
To easily make use of ServiceStack's Session (Cache & JSON Serializer) have your Controllers inherit from ServiceStackController (in MVC) or PageBase (in ASP.NET)
There is also new Authentication / Validation functionality added in ServiceStack which you can read about on the wiki:
Authentication and authorization
Validation
Using ASP.NET Session
Essentially ServiceStack is just a set of lightweight IHttpHandler's running on either an ASP.NET or HttpListener host. If hosted in IIS/ASP.NET (most common) it works like a normal ASP.NET request.
Nothing in ServiceStack accesses or affects the configured Caching and Session providers in the underlying ASP.NET application. If you want to enable it you would need to configure it as per normal in ASP.NET (i.e. outside of ServiceStack) see:
http://msdn.microsoft.com/en-us/library/ms178581.aspx
Once configured you can access the ASP.NET session inside a ServiceStack web service via the singleton:
HttpContext.Current.Session
Or alternatively via the underlying ASP.NET HttpRequest with:
var req = (HttpRequest)base.RequestContext.Get<IHttpRequest>().OriginalRequest;
var session = req.RequestContext.HttpContext.Session;
Although because of the mandatory reliance on XML config and degraded performance by default, I prefer to shun the use of ASP.NET's Session, instead opting to use the cleaner Cache Clients included with ServiceStack.
Basically the way Sessions work (ASP.NET included) is a cookie containing a unique id is added to the Response uniquely identifying the browser session. This id points to a matching Dictionary/Collection on the server which represents the browsers' Session.
The IRequiresSession interface you link to doesn't do anything by default, it simply is a way to signal to either a Custom Request Filter or base web service that this request needs to be authenticated (i.e. two places where you should put validation/authentication logic in ServiceStack).
Here's a Basic Auth implementation that looks to see if a web service is Secure and if so make sure they have authenticated.
Here's another authentication implementation that instead validates all services marked with an [Authenticate] attribute, and how to enable Authentication for your service by adding the Attribute on your Request DTO.
New Authentication Model in ServiceStack
The above implementation is apart of the multi-auth provider model included in the next version of ServiceStack. Here's the reference example showing how to register and configure the new Auth model in your application.
Authentication Strategies
The new Auth model is entirely an opt-in convenience as you can simply not use it and implement similar behaviour yourself using Request Filters or in base classes (by overriding OnBeforeExecute). In fact the new Auth services are not actually built-into ServiceStack per-se. The entire implementation lives in the optional ServiceStack.ServiceInterfaces project and implemented using Custom Request Filters.
Here are different Authentication strategies I've used over the years:
Mark services that need authentication with an [Attribute]. Likely the most idiomatic C# way, ideal when the session-id is passed via a Cookie.
Especially outside of a Web Context, sometimes using a more explicit IRequiresAuthentication interface is better as it provides strong-typed access to the User and SessionId required for Authentication.
You can just have a 1-liner to authenticate on each service that needs it - on an adhoc basis. A suitable approach when you have very few services requiring authentication.
That's a great and comprehensive answer by #mythz. However, when trying to access the ASP.NET session by HttpContext.Current.Session within a ServiceStack web service, it always returns null for me. That's because none of the HttpHandlers within ServiceStack are adorned with the IRequiresSessionState interface, so the .NET Framework does not provide us with the session object.
To get around this, I've implemented two new classes, both of which use the decorator pattern to provide us with what we need.
Firstly, a new IHttpHandler which requires session state. It wraps the IHttpHandler provided by ServiceStack and passes calls through to it...
public class SessionHandlerDecorator : IHttpHandler, IRequiresSessionState {
private IHttpHandler Handler { get; set; }
internal SessionHandlerDecorator(IHttpHandler handler) {
this.Handler = handler;
}
public bool IsReusable {
get { return Handler.IsReusable; }
}
public void ProcessRequest(HttpContext context) {
Handler.ProcessRequest(context);
}
}
Next, a new IHttpHandlerFactory which delegates the responsibility for generating the IHttpHandler to ServiceStack, before wrapping the returned handler in our new SessionHandlerDecorator...
public class SessionHttpHandlerFactory : IHttpHandlerFactory {
private readonly static ServiceStackHttpHandlerFactory factory = new ServiceStackHttpHandlerFactory();
public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated) {
var handler = factory.GetHandler(context, requestType, url, pathTranslated);
return handler == null ? null : new SessionHandlerDecorator(handler);
}
public void ReleaseHandler(IHttpHandler handler) {
factory.ReleaseHandler(handler);
}
}
Then, it's just a matter of changing the type attributes in the handlers in Web.config to SessionHttpHandlerFactory instead of ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack, and your web services should now have the ASP.NET session avaialble to them.
Despite the above, I fully endorse the new ISession implementation provided by ServiceStack. However, in some cases, on a mature product, it just seems too big a job to replace all uses of the ASP.NET session with the new implementation, hence this workaround!
Thanks #Richard for your answer above. I am running a new version of service stack and they have removed the ServiceStackHttpFactory with HttpFactory. Instead of having
private readonly static ServiceStackHttpHandlerFactory factory = new ServiceStackHttpHandlerFactory();
You need to have
private static readonly HttpHandlerFactory Factory = new HttpHandlerFactory();
Here is updated code for this service
using ServiceStack;
using System.Web;
using System.Web.SessionState;
namespace MaryKay.eCommerce.Mappers.AMR.Host
{
public class SessionHttpHandlerFactory : IHttpHandlerFactory
{
private static readonly HttpHandlerFactory Factory = new HttpHandlerFactory();
public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
{
var handler = Factory.GetHandler(context, requestType, url, pathTranslated);
return handler == null ? null : new SessionHandlerDecorator(handler);
}
public void ReleaseHandler(IHttpHandler handler)
{
Factory.ReleaseHandler(handler);
}
}
public class SessionHandlerDecorator : IHttpHandler, IRequiresSessionState
{
private IHttpHandler Handler { get; set; }
internal SessionHandlerDecorator(IHttpHandler handler)
{
Handler = handler;
}
public bool IsReusable
{
get { return Handler.IsReusable; }
}
public void ProcessRequest(HttpContext context)
{
Handler.ProcessRequest(context);
}
}
}
As of ServiceStack 4.5+ the HttpHandler can also support Async. Like so:
namespace FboOne.Services.Host
{
public class SessionHttpHandlerFactory : IHttpHandlerFactory
{
private static readonly HttpHandlerFactory Factory = new HttpHandlerFactory();
public IHttpHandler GetHandler(HttpContext context, string requestType, string url, string pathTranslated)
{
var handler = Factory.GetHandler(context, requestType, url, pathTranslated);
return handler == null ? null : new SessionHandlerDecorator((IHttpAsyncHandler)handler);
}
public void ReleaseHandler(IHttpHandler handler)
{
Factory.ReleaseHandler(handler);
}
}
public class SessionHandlerDecorator : IHttpAsyncHandler, IRequiresSessionState
{
private IHttpAsyncHandler Handler { get; set; }
internal SessionHandlerDecorator(IHttpAsyncHandler handler)
{
Handler = handler;
}
public bool IsReusable
{
get { return Handler.IsReusable; }
}
public void ProcessRequest(HttpContext context)
{
Handler.ProcessRequest(context);
}
public IAsyncResult BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
{
return Handler.BeginProcessRequest(context, cb, extraData);
}
public void EndProcessRequest(IAsyncResult result)
{
Handler.EndProcessRequest(result);
}
}
}
We are trying to implement MessagePack on our Web API. However I am having trouble finding a reliable up-to-date formatter. I found the WebApiContrib.Formatting.MsgPack formatter but the last update was in 2014 and when I try using it it throws "Method not found" exception.
I also looked at an example here but the code contains some method references that are no longer present in the nuget package.
There seems to be an updated ASP.NET Core library with a set of formatters but we are not looking to move to Core any time soon.
Does someone have a tip for a reliable formatter for MessagePack that would do the trick?
Implementing custom Media Type Formatter is pretty easy task if you have all serialization/deserialization code. So if you can't find suitable solution, you could implement your own. Here is working sample:
public class MessagePackFormatter : MediaTypeFormatter
{
public MessagePackFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/x-msgpack"));
}
public override bool CanReadType(Type type)
{
return true;
}
public override bool CanWriteType(Type type)
{
return true;
}
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
if (writeStream == null)
{
throw new ArgumentNullException(nameof(writeStream));
}
MessagePackSerializer.NonGeneric.Serialize(type, writeStream, value, ContractlessStandardResolver.Instance);
return Task.FromResult(0);
}
public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
if (type == null)
{
throw new ArgumentNullException(nameof(type));
}
if (readStream == null)
{
throw new ArgumentNullException(nameof(readStream));
}
var value = MessagePackSerializer.NonGeneric.Deserialize(type, readStream, ContractlessStandardResolver.Instance);
return Task.FromResult(value);
}
}
As you see it's very thin and just invokes MessagePackSerializer.NonGeneric class for serialization/deserialization. I'd suggest starting using such simple formatter and if you encounter some problems with it for specific cases, just tune the code to fix the issues. You could also examine existing implementation for .Net Core for handling some corner cases.