如何从Not a Controller创建一个通用的Unauthorized IHttpActionResult。

问题描述 投票:2回答:1

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

[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, OkContent(Status, Message). 其中大部分需要从 APIContoller. 仅仅为了创建一个对象,这似乎太过矫枉过正了。

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

c# authorization refit
1个回答
1
投票

如果你要分清责任,那么你应该分清 职责;

您的 UdpateUserProfile 方法应该是不可知的,它是从哪里被调用的。如果你想往下添加一个WPF客户端,你应该根本不需要改变这个类。在这种情况下,你将不会返回一个。IHttpActionResult你会做别的事的

因此,从你的方法中删除该依赖关系。让它通知它的任务是否成功。在这种情况下,a 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();

从你的Profile服务的返回类型来看,听起来你需要重构那个 UpdateUserProfile() 方法来删除那里的依赖关系。

为了达到最佳的安全性,你不应该显示用户无法更新的任何具体原因。然而,这绝对应该被记录在某个地方,这样你就可以跟踪任何未经授权的系统访问。

© www.soinside.com 2019 - 2024. All rights reserved.