I have a Web api that uses owin authentication with bearer tokens. I will have both web and wpf (vb) clients, that need to ask for image files from the api while authenticated. The images should not be returned on unauthenticated requests.
So far I have a working solution on returning an image while not authenticated:
My controller action in c#:
//[Authorize]
public HttpResponseMessage GetFile()
{
string localFilePath = "C:/Path/ImageOnServerDisk.png";
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = "myImage.png";
response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/png");
return response;
}
And this is how I display it on the web client:
<img src="/api/Secure/GetFile" id="img" />
This works fine, but of course when I uncomment the authorize attribute in the above action, the image file is not shown and I get a 401 (Unauthorized) message for the GET message calling for the GetFile action. This is because there is no access token on the GET request.
I could use jQuery to GET via ajax, but I don't know how to set the result into an img element.
How can I either set the access token for the http GET request calling an action in an img src, or set the image content into the img element in jQuery? Or is there a better way to do this altogether?
You can return one or the other, not both. Frankly, a WebAPI controller returns nothing but data, never a view page. A MVC controller returns view pages. Yes, your MVC code can be a consumer of a WebAPI, but not the other way around.
Web API assumes that authentication happens in the host. For web-hosting, the host is IIS, which uses HTTP modules for authentication. You can configure your project to use any of the authentication modules built in to IIS or ASP.NET, or write your own HTTP module to perform custom authentication.
I think "use jQuery to GET via ajax" will work. We can set token into request header. You can try below code for api controller:
var root = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
var path = Path.Combine(root, "App_Data/Koala.jpg");
var bytes = File.ReadAllBytes(path);
var base64 = Convert.ToBase64String(bytes);
return "data:image/jpeg;base64," + base64;
And below is some javascript snippet
$.ajax({
url: '//localhost:882/api/image',
type: "GET",
success: function (data) {
$('#testimg').attr('src', data);
$('#testimg').attr('style', 'display: block;');
}
});
Html
<img id="testimg" src="#" alt="Get from webapi" style="display: none;" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With