簡體   English   中英

在請求過濾器中結束響應時,ServiceStack設置響應DTO

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM