How can I create a custom HTTP status code from a

2019-02-27 06:29发布

问题:

I would like to return a custom HTTP status code from a RESTful WCF web service when a certain condition is met.

I do not want to use the standard HTTP status codes; instead, I would like to return e.g., a 514 status code which means something to the calling user.

Is this possible with WebOperationContext.Current.OutgoingResponse?

回答1:

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.



标签: c# wcf http