【发布时间】:2015-03-17 15:51:33
【问题描述】:
Nancy 文档似乎说 Pipelines.OnError 应该返回 null - 而 BeforeResponse 允许 null 和 Response 对象。
所有示例 like this one 和 StackOverflow 上的许多代码示例都显示在 OnError 中返回 Response,就像在 BeforeRequest 中一样。
当我尝试为 Pipelines.OnError 返回 HTTPStatus 字符串时,一切正常!
但是当我尝试返回一个响应时,我得到一个编译器错误: 运算符“+=”不能应用于“Nancy.ErrorPipeline”和“lambda 表达式”类型的操作数
我几乎完全模仿了 Nancy 示例中的代码,除了我的是 TinyIocContainer 而示例使用的是 StructureMap 容器和 StructureMap 派生的引导程序
这是我的代码:
const string errKey = "My proj error";
const string creationProblem = "Message creation (HTTP-POST)";
const string retrievalProblem = "Message retrieval (HTTP-GET)";
public void Initialize(IPipelines pipelines)
{
string jsonContentType = "application/json";
byte[] jsonFailedCreate = toJsonByteArray(creationProblem);
byte[] jsonFailedRetrieve = toJsonByteArray(retrievalProblem);
Response responseFailedCreate = new Response
{
StatusCode = HttpStatusCode.NotModified,
ContentType = jsonContentType,
Contents = (stream) =>
stream.Write(jsonFailedCreate, 0, jsonFailedCreate.Length)
};
Response responseFailedRetrieve = new Response
{
StatusCode = HttpStatusCode.NotFound,
ContentType = jsonContentType,
Contents = (stream) =>
stream.Write(jsonFailedRetrieve, 0, jsonFailedRetrieve.Length)
};
// POST - error in Create call
pipelines.OnError += (context, exception) =>
{
// POST - error during Create call
if (context.Request.Method == "POST")
return responsefailedCreate;
// GET - error during Retrieve call
else if (context.Request.Method == "GET")
return responseFailedRetrieve;
// All other cases - not supported
else
return HttpStatusCode.InternalServerError;
};
}
private byte[] toJsonByteArray(string plainString)
{
string jsonString = new JObject { { errKey, plainString } }.ToString();
byte[] result = Encoding.UTF8.GetBytes(jsonString);
return result;
}
【问题讨论】: