HttpListener now returns 404 if a route isn't found instead of bad request. Added WithRedirect and WithHtml extensions. Bumped nuget version to 1.1.1

This commit is contained in:
MattMo 2022-07-26 20:26:53 -07:00
parent 56a17a3c66
commit 77f13ac7ae
3 changed files with 41 additions and 3 deletions

@ -65,6 +65,22 @@ namespace MontoyaTech.Rest.Net
return response;
}
/// <summary>
/// Sets the response content type to html and writes the given html to it.
/// </summary>
/// <param name="response"></param>
/// <param name="html"></param>
/// <returns>This response.</returns>
public static HttpListenerResponse WithHtml(this HttpListenerResponse response, string html)
{
response.ContentType = "text/html; charset=utf-16";
var bytes = Encoding.Unicode.GetBytes(html);
response.OutputStream.Write(bytes, 0, bytes.Length);
return response;
}
/// <summary>
/// Sets the status code for a given response.
/// </summary>
@ -187,5 +203,27 @@ namespace MontoyaTech.Rest.Net
return response;
}
/// <summary>
/// Sets a redirect for a given response.
/// </summary>
/// <param name="response"></param>
/// <param name="url"></param>
/// <returns>This response.</returns>
public static HttpListenerResponse WithRedirect(this HttpListenerResponse response, string url)
{
try
{
response.StatusCode = (int)HttpStatusCode.Redirect;
response.AddHeader("Location", url);
return response;
}
catch
{
return response;
}
}
}
}

@ -17,8 +17,8 @@
<AssemblyName>MontoyaTech.Rest.Net</AssemblyName>
<RootNamespace>MontoyaTech.Rest.Net</RootNamespace>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
<Version>1.1.0</Version>
<PackageReleaseNotes>Upgraded project to DotNet 6 and added an exception catch around the main listener thread to prevent crashes where the entire Reset service goes down.</PackageReleaseNotes>
<Version>1.1.1</Version>
<PackageReleaseNotes>HttpListener now returns NotFound if no route was found. Added WithRedirect and WithHtml extensions.</PackageReleaseNotes>
</PropertyGroup>
<ItemGroup>

@ -156,7 +156,7 @@ namespace MontoyaTech.Rest.Net
catch { }
if (!handled)
ctx.Response.WithStatus(HttpStatusCode.BadRequest);
ctx.Response.WithStatus(HttpStatusCode.NotFound);
if (close)
ctx.Response.Close();