Skip to content

Instantly share code, notes, and snippets.

@josephhanson
Last active December 26, 2016 16:58
Show Gist options
  • Save josephhanson/0822bb151e005ed3c865d2701bf4c415 to your computer and use it in GitHub Desktop.
Save josephhanson/0822bb151e005ed3c865d2701bf4c415 to your computer and use it in GitHub Desktop.
Workaround to Use HTTP Status Codes When Working with a Partial SPA in ASP.NET MVC
public class MvcApiJsonRequest : JsonResult {
private readonly int _httpStatusCode;
private readonly string _invalidHttpStatusCodeMessage = "set httpStatusCode to an allowed http status code";
public MvcApiJsonRequest() {
_httpStatusCode = 200;
}
public MvcApiJsonRequest(object content) : this(200, content) {}
public MvcApiJsonRequest(int httpStatusCode) : this(httpStatusCode, null) {}
public MvcApiJsonRequest(int httpStatusCode, object content) {
// TODO: better method name
IsStatusCodeAllowed(httpStatusCode);
_httpStatusCode = httpStatusCode;
Data = content;
}
public int HttpStatusCode => _httpStatusCode;
public override void ExecuteResult(ControllerContext context) {
context.HttpContext.Response.StatusCode = HttpStatusCode;
base.ExecuteResult(context);
}
private void IsStatusCodeAllowed(int httpStatusCode) {
switch (httpStatusCode) {
case 0:
throw new ArgumentOutOfRangeException(nameof(httpStatusCode), _invalidHttpStatusCodeMessage);
case 200:
break;
case 201:
break;
case 400:
break;
default:
throw new ArgumentOutOfRangeException(nameof(httpStatusCode), _invalidHttpStatusCodeMessage);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment