我刚刚开始使用ServiceStack来实现API示例并经历了很多示例,一些示例从服务返回HttpResult而其他示例返回ResponseDTO,哪一个更受欢迎?
仅返回响应DTO是首选,这基本上意味着您对默认行为感到满意,并且您的服务将按原样返回响应主体,序列化为请求的内容类型.
HttpResult适用于您的服务除了响应之外还需要添加其他HTTP自定义(例如其他HTTP标头) - 但它不会更改HTTP响应主体的有线格式(除非您更改将使用的内容类型)更改响应序列化的内容).
虽然HttpResult只是定制响应的一种方法,但以下是其他一些方法:
public class HelloService : Service
{
public object Get(Hello request)
{
//1. Returning a custom Response Status and Description with Response DTO body:
var responseDto = ...;
return new HttpResult(responseDto, HttpStatusCode.Conflict) {
StatusDescription = "Computer says no",
};
//2. Throw or return a HttpError:
throw new HttpError(System.Net.HttpStatusCode.Conflict, "SomeErrorCode");
//3. Modify the Request's IHttpResponse
base.Response.StatusCode = (int)HttpStatusCode.Redirect;
base.Response.AddHeader("Location", "http://path/to/new/uri");
}
//4. Using a Request or Response Filter
[AddHeader(ContentType = "text/plain")]
public string Get(Hello request)
{
return "Hello, {0}!".Fmt(request.Name);
}
}
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅自定义HTTP响应 Wiki.
| 归档时间: |
|
| 查看次数: |
1602 次 |
| 最近记录: |