4

We have a asp.net mvc application that uses SignalR. SignalR is hosted in a SelfHosted Service using OWIN.

I have created a cookie on the MVC side, the cookie content is a JSON string of a the following class:

public class UserCookie
{
    public int    UserId    { get; set; }
    public string Username  { get; set; }
}

I create the cookie in the MVC Controller:

var userCookie = new UserCookie
{
  UserId   = 999999,
  Username = "John Doe"
};

var serializeValue = JsonConvert.SerializeObject(userCookie);

Response.Cookies.Add(new System.Web.HttpCookie("MyCookie", JsonConvert.SerializeObject(userCookie)));

I can see the Cookie value in Chrome and Fiddler:

enter image description here

I Can Deserialize the cookie on the MVC side:

enter image description here

But on the SelfHosted OWIN side I get the following error:

enter image description here

It seems like the OWIN side only gets part of the cookie as the value is {\"UserId\":999999

Here is my startup class for OWIN:

public class Startup
{
    public void Configuration(IAppBuilder app) 
    {   
        app.UseCors(CorsOptions.AllowAll);            

        app.Use(async (context, next) => 
        {
            JsonConvert.DeserializeObject<Common.Users.UserCookie>(context.Request.Cookies["MyCookie"]);

            await next();
        });

        app.MapSignalR();
    }
}

The JsonConvert.DeserializeObject<Common.Users.UserCookie>(context.Request.Cookies["MyCookie"]); is where I am getting the error.

Must I encode the cookie value for it to work on the OWIN side? Or is there something obvious that I am missing?

UPDATE

Encoding the JSON as base64 and using it as the value for the cookie(instead of the JSON value) seems to solve the issue as I can now successfully deserialize the cookie value.

Tjaart van der Walt
  • 5,149
  • 2
  • 30
  • 50
  • [Possible OWIN bug](http://stackoverflow.com/questions/20737578/asp-net-sessionid-owin-cookies-do-not-send-to-browser) – Oguz Ozgul Nov 23 '15 at 14:55
  • 1
    You should not be using JSON in a cookie, it uses invalid characters. I recomend Base64 or Url encoding the value. – Tratcher Nov 23 '15 at 17:45
  • @Tratcher I will keep that in mind but this still does not explain why MVC can deserialize the value and OWIN can not? – Tjaart van der Walt Nov 23 '15 at 19:30
  • 1
    The parsing behavior for invalid data is undefined, so you will get different results with different parsers. – Tratcher Nov 25 '15 at 02:54

0 Answers0