<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>asp.net core easy tips &#8211; ASP.NET Hosting Reviews and Guides</title>
	<atom:link href="https://topreviewhostingasp.net/tag/asp-net-core-easy-tips/feed/" rel="self" type="application/rss+xml" />
	<link>https://topreviewhostingasp.net</link>
	<description>ASP.NET Hosting &#124; Reviews &#124; Tips &#38; Tutorial</description>
	<lastBuildDate>Wed, 22 Mar 2017 03:14:42 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://topreviewhostingasp.net/wp-content/uploads/2017/01/cropped-trhaico-32x32.png</url>
	<title>asp.net core easy tips &#8211; ASP.NET Hosting Reviews and Guides</title>
	<link>https://topreviewhostingasp.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>ASP.NET Core Tutorial &#8211; Status Code with Empty Response</title>
		<link>https://topreviewhostingasp.net/asp-net-core-tutorial-status-code-empty-response/</link>
					<comments>https://topreviewhostingasp.net/asp-net-core-tutorial-status-code-empty-response/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Fri, 17 Mar 2017 02:44:05 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[asp.net core easy tips]]></category>
		<category><![CDATA[asp.net core tips]]></category>
		<category><![CDATA[asp.net core tutorial]]></category>
		<category><![CDATA[status code asp.net core]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=421</guid>

					<description><![CDATA[If you create JSON APIs, you know that sometimes it is useful to return empty response with just status code set. For example when user calls the API to get a document with id 123 and he doesn’t have the rights to this particular document, it is a good practice to return with a status ‘403 Forbidden’. When you [&#8230;]]]></description>
										<content:encoded><![CDATA[<p>If you create JSON APIs, you know that sometimes it is useful to return empty response with just status code set. For example when user calls the API to get a document with id 123 and he doesn’t have the rights to this particular document, it is a good practice to return with a status ‘403 Forbidden’. When you do that, you don’t need to add anything to the response &#8211; status code is just enough.</p>
<p>My previous project was build with <a href="https://github.com/NancyFx/Nancy/wiki">NancyFx</a>, which makes it trivial:</p>
<pre class="lang:default decode:true">Get["/products/{id}"] = parameters =&gt;;
{
    Product item = repository.Get(parameters.id);
    if (item == null)
    {
        return HttpStatusCode.NotFound;
    }
    return item;
};</pre>
<p>In the ASP.NET 4.6 you had an option to throw a special exception which had a field for response status code:</p>
<pre class="lang:default decode:true">public Product GetProduct(int id)
{
    Product item = repository.Get(id);
    if (item == null)
    {
        throw new HttpResponseException(HttpStatusCode.NotFound);
    }
    return item;
}</pre>
<p>Right now I am working on an API built with the new ASP.NET Core and I wanted to do the same. It quickly turned out there is no HttpResponseException class there anymore. There were basically two simple options:</p>
<ol>
<li>Change controller method signature to return IActionResult **and return **StatusCode(403) &#8211; I didn’t like it as I want to have proper type returned from my controller methods&lt;/li&gt;</li>
<li>Set the Response.StatusCode manually and return null (or 0 if the method returns int) &#8211; also didn’t like it as you can’t easily unit test it.&lt;/li&gt;</li>
</ol>
<p>After some googling and searching on StackOverflow, I found a nice solution for this problem &#8211; to create a new type of exception: HttpStatusCodeException, containing a field for the status code and a middleware, which will catch these exceptions and reformat the response to just contain the status code.</p>
<p>This is the code for both things:</p>
<pre class="lang:default decode:true ">public class ErrorHandlerMiddleware
{
    public class HttpStatusCodeException : Exception
    {
        public HttpStatusCode StatusCode { get; set; }

        public HttpStatusCodeException(HttpStatusCode statusCode)
        {
            StatusCode = statusCode;
        }
    }

    private readonly RequestDelegate _next;

    public ErrorHandlerMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            await _next(context);
        }
        catch (HttpStatusCodeException exception)
        {
            context.Response.StatusCode = (int) exception.StatusCode;
            context.Response.Headers.Clear();
        }
    }
}</pre>
<p>As you can see, the HttpStatusCodeException takes standard HttpStatusCode as a constructor parameter and then it is read and returned by the middleware in the catch statement.</p>
<p>I like this solution because it’s very simple and elegant. I don’t return any content (even null) from the API methods and have proper type checking in the controller methods.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/asp-net-core-tutorial-status-code-empty-response/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
