Last active
March 22, 2018 09:32
-
-
Save sakapon/8d0b561449af2d8103b1ee374b44376a to your computer and use it in GitHub Desktop.
AspNetWebApiSample/SampleWebApi/Controllers/RandomTextController.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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