2

We are using asp.net web api odata entitysetcontroller to get user profiles. The url that represents a single user profile looks like this

http://www.domain.com/api/org/staff(123)

Now bussiness asked us to provide user image as part of the user profile. So I added a odata action method to the exisitng controller.

var staff = builder.EntitySet<Contact>("staff");  //regiester controller
var staffAction = staff.EntityType.Action("picture");  //register action method          
staffAction.Returns<System.Net.Http.HttpResponseMessage>();

The odata action method in controller as below

[HttpPost]
public HttpResponseMessage Picture([FromODataUri] int key)
    {
        var folderName = "App_Data/Koala.jpg";
        string path = System.Web.HttpContext.Current.Server.MapPath("~/" + folderName);

        using (FileStream mem = new FileStream(path,FileMode.Open))
        {
            StreamContent sc = new StreamContent(mem);
            HttpResponseMessage response = new HttpResponseMessage();                
            response.Content = sc;
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
            response.Content.Headers.ContentLength = mem.Length;
            response.StatusCode = HttpStatusCode.OK;
            return response;
        }
    }

I tried the following url to test and the method executed successfully. However the problem is that I always recieve the error message with status 504 as a final response.

http://www.domain.com/api/org/staff(123)/picture

"ReadResponse() failed: The server did not return a response for this request." 

1 Answer 1

4

I think the problem is with closing the FileStream.

Do not close the stream as Web API's hosting layers take care of closing it. Also, you need not set the content-length explicitly.StreamContent sets this for you.

[HttpPost]
public HttpResponseMessage Picture([FromODataUri] int key)
{
    var folderName = "App_Data/Koala.jpg";
    string path = System.Web.HttpContext.Current.Server.MapPath("~/" + folderName);

    StreamContent sc = new StreamContent(new FileStream(path,FileMode.OpenRead));
        HttpResponseMessage response = new HttpResponseMessage();                
        response.Content = sc;
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpeg");
        response.StatusCode = HttpStatusCode.OK;
        return response;
}
Sign up to request clarification or add additional context in comments.

2 Comments

@Kiran-Challa What about uploading files? I couldn't find any good example for doing this with wep api odata
I've got the same question as @CoffeeCode. What are you doing for upload? Not finding great examples on the web. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.