A day with .Net

My day to day experince in .net

Archive for the ‘Web API’ Category

Return Json from a Web Api via HttpResponseMessage

Posted by vivekcek on June 26, 2016

This is a small tip to send json data through HttpResponseMessage.

First create the helper class in your Web Api Controller.

public class JsonContent : HttpContent
    {

        private readonly MemoryStream _Stream = new MemoryStream();
        public JsonContent(object value)
        {

            Headers.ContentType = new MediaTypeHeaderValue("application/json");
            var jw = new JsonTextWriter(new StreamWriter(_Stream));
            jw.Formatting = Formatting.Indented;
            var serializer = new JsonSerializer();
            serializer.Serialize(jw, value);
            jw.Flush();
            _Stream.Position = 0;

        }
        protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
        {
            return _Stream.CopyToAsync(stream);
        }

        protected override bool TryComputeLength(out long length)
        {
            length = _Stream.Length;
            return true;
        }
    }

Now try this in your Action method.

public HttpResponseMessage Delete(int id)
        {
            return new HttpResponseMessage()
            {
                Content = new JsonContent(new
                {
                    Name = "Vivek",
                    Address = "Address",
                    Message = "Any Message" //return exception
                })
            };
        }

Posted in MVC, Web API | Tagged: , , | 1 Comment »

Web API inside an MVC Area

Posted by vivekcek on May 7, 2016

This is strange thing, i faced when added a Web Api controller inside an area of my production code.
I was using the defualt Web Api route pattern in WebApiConfig.cs

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

Unfortunately when i tried to access the path via Jquery Ajax, I got the path not found exception.

This was the path i tried.
http://localhost:56109/api/MySecond

Ok, so i thought as my API controller is under an Area, i should try this way.

http://localhost:56109/api/MyArea/MySecond

Ooops!! still path not found, hmm. I added below code in my AreaRegistraion.Cs file.
Don’t forget to add refrence of “System.Web.Http”

context.Routes.MapHttpRoute(
"FileUpload",
"MyArea/api/{controller}/{id}",
new { AreaName = "MyArea", id = UrlParameter.Optional }
);

Wow now this path is working fine “http://localhost:56109/api/MyArea/MySecond

NB: This was experience in a production app developed with MVC 5 and VS 2013, Anyway i was not able to reproduce this in VS 2015.
As far as my understanding Web Api controllers and routing is independent of MVC Area.

Posted in MVC, Web API | Tagged: , , | Leave a Comment »