ServiceStack自定义HTTP响应ADD消息和errorCode

时间:2014-12-05 16:28:03

标签: c# http http-post servicestack httpresponse

我正在尝试为我的网络服务添加带有HTTP错误响应的自定义消息。我希望有类似的东西:

  

远程服务器返回错误:(406)Not Acceptable。 自定义消息:{ErrorCode:2,错误:“无用户名”}

我试过了:

throw new HttpError(System.Net.HttpStatusCode.NotAcceptable, "No Username");

而且:

string ErrorMessage = "ErrorCode = 2, Error = No Username";
throw new HttpError(406, ErrorMessage);

而且:

var responseDto = new UserCreatedResponse { ErrorCode = 2, Error = "No Username" };
                    return new HttpResult(responseDto, HttpStatusCode.NotAcceptable)
                    {
                        StatusDescription = "Computer says no",
                    };

我关注了serviceStack doc https://github.com/ServiceStack/ServiceStack/wiki/Customize-HTTP-Responses,但我无法正确理解,我只得到Http错误“远程服务器返回错误:(406)Not Acceptable。”但不是自定义消息。 我误解了什么吗? 感谢

2 个答案:

答案 0 :(得分:1)

你的第一个例子是正确的,例如这是CustomHttpErrorService

的测试实现
public class CustomHttpError
{
    public int StatusCode { get; set; }
    public string StatusDescription { get; set; }
}

public class CustomHttpErrorResponse
{
    public string Custom { get; set; }
    public ResponseStatus ResponseStatus { get; set; }
}

public class CustomHttpErrorService : Service
{
    public object Any(CustomHttpError request)
    {
        throw new HttpError(request.StatusCode, request.StatusDescription);
    }
}

您可以在http://test.servicestack.net

的已部署网站上进行测试

返回预期的响应状态代码和说明:

HTTP/1.1 406 CustomDescription
Cache-Control: private
Content-Type: application/json; charset=utf-8
Vary: Accept
Server: Microsoft-IIS/8.5
X-Powered-By: ServiceStack/4.00 Win32NT/.NET
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Fri, 05 Dec 2014 22:41:23 GMT
Content-Length: 449

这适用于IIS,IIS Express以及所有ServiceStack Self Hosts。但不幸的是,VS.NET Web Development Server不支持设置自定义状态描述。

答案 1 :(得分:-1)

我不知道我是否会正确回答你

你可以尝试这样的事情

抛出新的HttpError。 (在点之后它会显示几个错误)

e.g

HttpError.NotFound("将自定义消息放在此处")

HttpError.Conflict("将自定义消息放在这里")