How can I return a custom HTTP status code from a WCF REST method?
There is a WebOperationContext
that you can access and it has a OutgoingResponse
property of type OutgoingWebResponseContext
which has a StatusCode
property that can be set.
WebOperationContext ctx = WebOperationContext.Current;
ctx.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
How can I create a custom HTTP status code from a WCF REST method?
OutgoingResponse.StatusCode is where you'd set the status code, but it's an HttpStatusCode enum, not an integer value.
You could cast a custom value int to HttpStatusCode, but I'm not sure what the framework would do with it; most likely it would throw, but it can't hurt to try.
Although the HTTP spec doesn't disallow custom response codes, it's probably not a good idea to go that route unless you must. Perhaps a custom response header would be better?
If you must go the custom status code route, another option might be to use ASP.NET compatibility mode. That would allow you to use HttpContext.Current.Response.StatusCode, which is an int. You'd have to be hosted in IIS for this to work, however, and I don't know your architecture.
Returning HttpStatus codes with message from WCF Rest service that IParameterInspector AfterCall can handle
Ok after a lot of searching I found this question and this answer
So to summarise: a call to a little method like:
public void SetResponseHttpStatus(HttpStatusCode statusCode)
{
var context = WebOperationContext.Current;
context.OutgoingResponse.StatusCode = statusCode;
}
...before each return that isn't a plain 200 response should do it.
How do I return HTTP status code 420 from my WCF service?
You can cast any int
value to an enum (well, one with int
as its base type) - it doesn't have to be a "valid" value - so you can try:
ctx.OutgoingResponse.StatusCode = (System.Net.HttpStatusCode)420;
See C# Language Specification, version 5, section 1.10:
The set of values that an enum type can take on is not limited by its enum members. In particular, any value of the underlying type of an enum can be cast to the enum type and is a distinct valid value of that enum type.
How can I read the custom HTTP status code using WCF REST?
WCF is designed for all sorts of channels so this is not a high level object
You can access it though with something like this
factory.Endpoint.Behaviors.Add(new WebHttpBehavior());
IMyContract proxy = factory.CreateChannel();
using (OperationContextScope scope = new OperationContextScope((IContextChannel)proxy)) {
proxy.MyMethod("Some data"));
var responseCode = WebOperationContext.Current.IncomingResponse.StatusCode;
}
((IClientChannel)proxy).Close();
factory.Close();
how to send status code as response for Unauthorized requests to WCF rest service
If you're using WCF Rest Starter kit you can also do:
throw new Microsoft.ServiceModel.Web.WebProtocolException(System.Net.HttpStatusCode.Unauthorized, "message", ex);
That method has some more overloads if you need.
What is the best way to return errors from a WCF service in a RESTful way?
Send the proper response code and you can supply the custom error message in the body of the response.
Causing HTTP error status to be returned in WCF
I found a helpful article here: http://zamd.net/2008/07/08/error-handling-with-webhttpbinding-for-ajaxjson/. Based on that, this is what I came up with:
public class HttpErrorsAttribute : Attribute, IEndpointBehavior
{
public void AddBindingParameters(
ServiceEndpoint endpoint,
BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(
ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
}
public void ApplyDispatchBehavior(
ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
var handlers = endpointDispatcher.ChannelDispatcher.ErrorHandlers;
handlers.Clear();
handlers.Add(new HttpErrorHandler());
}
public void Validate(ServiceEndpoint endpoint)
{
}
public class HttpErrorHandler : IErrorHandler
{
public bool HandleError(Exception error)
{
return true;
}
public void ProvideFault(
Exception error, MessageVersion version, ref Message fault)
{
HttpStatusCode status;
if (error is HttpException)
{
var httpError = error as HttpException;
status = (HttpStatusCode)httpError.GetHttpCode();
}
else if (error is ArgumentException)
{
status = HttpStatusCode.BadRequest;
}
else
{
status = HttpStatusCode.InternalServerError;
}
// return custom error code.
fault = Message.CreateMessage(version, "", error.Message);
fault.Properties.Add(
HttpResponseMessageProperty.Name,
new HttpResponseMessageProperty
{
StatusCode = status,
StatusDescription = error.Message
}
);
}
}
}
This allows me to add a [HttpErrors]
attribute to my service. In my custom error handler, I can ensure that the HTTP status codes I'd like to send are sent.
Related Topics
Should You Declare Methods Using Overloads or Optional Parameters in C# 4.0
What Is the Fastest Way to Combine Two Xml Files into One
JSON String to CSV and CSV to JSON Conversion in C#
Creating Delegates Manually VS Using Action/Func Delegates
Could Not Load File or Assembly 'Microsoft.Reportviewer.Common, Version=11.0.0.0
Cancelling a Task Is Throwing an Exception
Create Xml Nodes Based on Xpath
Webapi Streamcontent VS Pushstreamcontent
How to Make a Call to My Wcf Service Asynchronous
Should I Use Two "Where" Clauses or "&&" in My Linq Query
How to Ignore Null Values for All Source Members During Mapping in Automapper 6
How to Throttle Event Stream Using Rx
ASP.NET MVC 4 Multiple Post via Different Forms