简体   繁体   中英

web api convert every response to base64

I have a code

        [HttpGet]
        public IHttpActionResult Search()
        {
            return Ok(Convert.ToBase64String(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(db.view_users.Take(1)))));
        }

I want send to client in base64, but it hard if i must convert manually in every return.

if there a way so i can automatically convert every return to base 64, how to do that?

so i can just use natural code like this :

        [HttpGet]
        public IHttpActionResult Search()
        {
            return Ok(db.view_users.Take(1));
        }

but still return the same result in base64

thanks

You can create ActionFilter like this:

public class Base64FilterAttribute : ActionFilterAttribute
{
    public override async Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
    {
        if (actionExecutedContext.Exception == null)
        {
            var bytes = await actionExecutedContext.Response.Content.ReadAsByteArrayAsync();
            var base64 = Convert.ToBase64String(bytes);
            actionExecutedContext.Response.Content = new StringContent(base64); 
        }

        await base.OnActionExecutedAsync(actionExecutedContext, cancellationToken);
    }
}

and then mark you controllers with this attribute or register as global filter.

If you are using OWIN You can also create OWIN midelware for that https://docs.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM