Setting Result in the context of ChallengeAsync method in an authentication filter

前端 未结 1 1845
甜味超标
甜味超标 2021-01-12 07:51

This question is related to the answer I have provided here. OP\'s comment got me thinking a bit. I suggested using a class implementing IHttpActionResult like

相关标签:
1条回答
  • 2021-01-12 08:10

    The intent was to use the first approach rather than the second. For example, see the Basic Authentication sample (also available for MVC), which follows the first approach: http://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/BasicAuthentication/ReadMe.txt

    The second approach mostly works. I wouldn't be too concerned about the performance standpoint; either way you're allocating one action result object and one response message object, so I'm not seeing much difference there.

    However, there are a couple of reasons I'd recommend the first approach:

    1. The second approach won't work the same way in MVC. Both MVC and Web API have authentication filters, and they basically work the same way. But in MVC, there isn't an equivalent to ResponseMessageResult (the HttpContext is updated as needed, rather than returning a HttpResponseMessage that could be replaced by each caller going up the stack). If you have an MVC implementation of your authentication filter, you'd likely end up doing the first approach there anyway.
    2. It slightly changes the pipeline behavior from what's intended. The code in ChallengeAsync runs earlier than the code in the context.Result that it returns. For example, if the code changed a property on the HttpRequestMessage and that impacted a later filter's ChallengeAsync logic, the behavior could be different than what's intended.

    The framework definitely could make it easier to implement the interface; feel free to vote on this work item: https://aspnetwebstack.codeplex.com/workitem/1456

    0 讨论(0)
提交回复
热议问题