如何从非控制器创建通用的UnAuthorized IHttpActionResult

时间:2016-12-19 21:24:20

标签: c#

我有一个API调用,它使用Refit返回IHttpActionResult

[Patch("/api/userprofile/")]
[Headers("Authorization: Bearer")]
Task<IHttpActionResult> UpdateUserProfile(UserProfile user);  

我在一个单独的DLL中创建了一个单独的类来处理API调用。

public async Task<IHttpActionResult> UpdateUserProfile(UserProfile profile)
{
    if (HttpContext.Current.Request.IsAuthenticated)
    {
        var ups = ApiServiceFactory.GetUserProfileService();
        var result = ups.UpdateUserProfile(profile);

        return result.Result;
    }
    return ???;
}

此类当前不是从APIController派生的,因此如何创建一个继承自IHttpActionResult的对象。我尝试了ResponseMessage,HttpResponseMessage,Ok和Conent(状态,消息)。其中大部分都需要来自APIContoller。仅仅创建一个对象似乎有点过分。

那么如何创建一个从IHttpActionResult继承的对象,从普通的类/方法返回类似401的东西?

1 个答案:

答案 0 :(得分:0)

如果您要分离责任,那么您应该将所有职责分开。

您的UdpateUserProfile方法应该不知道调用它的位置。如果您想要添加一个WPF客户端,您根本不必更改此类。在那种情况下,你不会回归IHttpActionResult,你将会做其他事情。

因此,从您的方法中删除该依赖项。让它通知它的任务是否成功。在这种情况下,bool可能更适合返回值。如果要返回其他信息,可以创建一个简单模型来封装要返回的任何其他数据。

public class AuthorizationResult
{
    public bool Result { get; set; }
    public string Message { get; set; }

    public AuthorizationResult()
    {
        Result = true;
    }

    public AuthorizationResult(string errorMessage)
    {
        Result = false;
        Message = errorMessage;
    }
}

然后在你的服务中。

public async Task<AuthorizationResult> UpdateUserProfile(UserProfile profile)
{
    try
    {
        var ups = ApiServiceFactory.GetUserProfileService();
        var result = ups.UpdateUserProfile(profile);

        return new AuthorizationResult();
    }
    catch (Exception ex)
    {
        // Just an example of how to get a message.
        // Depending on your implementation, you might be returning a 
        // message from UpdateUserProfile(profile).
        return new AuthorizationResult(ex.Message);
    }
}

然后,在您的API控制器内部,即将它与技术紧密结合,因为它直接在那里使用。此处还应包括您检查用户是否经过身份验证的检查,因为您的服务对于验证用户的机制并不了解。

var result = HttpContext.Current.Request.IsAuthenticated ?
                separateClass.UpdatedUserProfile(profile) :
                new AuthorizationResult("User is not authenticated");

return result.Result ? Ok() : Unauthorized();

根据您的个人资料服务的返回类型判断,您需要重构UpdateUserProfile()方法以及删除其中的依赖关系。

为了获得最佳安全性,您不应显示无法更新用户的任何具体原因。但是,这绝对应该记录在某处,以便您可以跟踪对系统的任何未经授权的访问。