[英]ServiceStack set Response DTO when ending the response in Request Filter
我使用ServiceStack创建一个API。 我想在请求过滤器中执行身份验证。 我创建了一个继承RequestFilterAttribute并重写方法的类
void Execute(IRequest req, IResponse res, object requestDto)
在身份验证失败时的替代中,我希望阻止请求继续使用服务方法,并且我想返回特定消息。 为了结束请求,我可以使用以下方法之一:
res.Close();
res.End();
res.EndHttpHandlerRequest();
res.EndRequest();
res.EndRequestWithNoContent();
它们阻止了服务中方法的执行。 结束响应后,我希望有一条带有消息的特定DTO。 因此,在结束响应之前,我将DTO对象分配给该属性
res.Dto = myResponseDto;
但是,API调用的结果没有任何数据。 有人可以帮助阻止筛选器中的请求到达ServiceStack服务实现,但返回所需的DTO响应对象吗?
使用过滤器,您必须处理原始响应。 因此,如果要在过滤器中结束响应并返回DTO响应,则需要在调用EndRequest
方法之前将DTO对象Write
响应。
如果发送的是Unauthorized
错误,则将状态代码设置为HttpStatusCode.Unauthorized
(401)通常是客户端识别其请求失败所需的全部操作。
public override void Execute(IRequest req, IResponse res, object requestDto)
{
// Perform you filter actions
if(authorised)
return;
// Not authorised, return some object
var responseDto = new {
SomeValue = "You are not authorised to do that."
};
// Set the status code
res.StatusCode = (int)HttpStatusCode.Unauthorized;
// You may need to handle other return types based on `req.AcceptTypes`
// This example assumes JSON response.
// Set the content type
res.ContentType = "application/json";
// Write the object
res.Write(responseDto.toJson());
// End the request
req.EndRequest();
}
希望能有所帮助。
您可以按照以下说明进行操作,其中res.Dto
可以更改为您想要的任何形式:
res.ContentType = req.ResponseContentType;
res.StatusCode = (int)HttpStatusCode.Unauthorized;
res.Dto = DtoUtils.CreateResponseDto(requestDto, new ResponseStatus("401", "Unauthorized"));
res.EndRequest();
如果不需要在响应中嵌入数据,则可以简单地使用throw new AuthenticationException("Error reason");
在您的过滤器中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.