Skip to content

Instantly share code, notes, and snippets.

@sakapon
Last active March 22, 2018 09:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sakapon/8d0b561449af2d8103b1ee374b44376a to your computer and use it in GitHub Desktop.
Save sakapon/8d0b561449af2d8103b1ee374b44376a to your computer and use it in GitHub Desktop.
AspNetWebApiSample/SampleWebApi/Controllers/RandomTextController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
namespace SampleWebApi.Controllers
{
[RoutePrefix("api")]
public class RandomTextController : ApiController
{
static readonly Random random = new Random();
[HttpGet]
[Route("NewBytes1/{count:int:range(0,64)}")]
[ResponseType(typeof(string))]
public HttpResponseMessage NewBytes1(int count)
{
var content = CreateBytesString(count);
var response = Request.CreateResponse();
response.Content = new StringContent(content);
return response;
}
[HttpGet]
[Route("NewBytes2/{count:int:range(0,64)}")]
[ResponseType(typeof(string))]
public IHttpActionResult NewBytes2(int count)
{
var content = CreateBytesString(count);
return new TextResult(content, Request);
}
static string CreateBytesString(int count)
{
var bytes = new byte[count];
random.NextBytes(bytes);
return string.Join("\n", bytes);
}
}
public class TextResult : IHttpActionResult
{
public string Content { get; }
public HttpRequestMessage Request { get; }
public TextResult(string content, HttpRequestMessage request)
{
Content = content;
Request = request;
}
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
var response = Request.CreateResponse();
response.Content = new StringContent(Content);
return Task.FromResult(response);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment