gpt4 book ai didi

c# - 在 Web api Controller 中使用身份验证过滤器发送 json 响应?

转载 作者:行者123 更新时间:2023-11-30 21:43:02 24 4
gpt4 key购买 nike

我的 Controller 中有一个身份验证过滤器

[ArcGISAuthentication]

我已经定义了如下过滤器

public class ArcGISAuthenticationAttribute : Attribute, IAuthenticationFilter
{
public Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken)
{
return Task.Run(async () =>
{
var queryParameters = HttpUtility.ParseQueryString(context.Request.RequestUri.Query);
var token = queryParameters["token"];
if (!string.IsNullOrWhiteSpace(token))
{
var userInfo = await CommunityManager.GetUserInfoAsync(token);
context.Principal = new ArcGISUserPrincipal(userInfo, token);
context.Request.SetUserPrincipal(context.Principal);
}
else{
//What shoudld I do here to send a json response
}
});
}

public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken)
{
return Task.Run(() => { });
}

public ArcGISAuthenticationAttribute()
{

}
}

问题是我想在身份验证失败时发送一个 json 响应。与上面 AuthenticateAsync 中的 else 语句一样。

我该怎么做?

最佳答案

创建自定义错误结果

public class ErrorResult : IHttpActionResult {
public ErrorResult(HttpRequestMessage request, string message, HttpStatusCode status = HttpStatusCode.InternalServerError, string reasonPhrase = "Internal Server Error") {
ReasonPhrase = reasonPhrase;
Request = request;
Message = message;
Status = status;
}

public HttpStatusCode Status { get; private set; }

public string ReasonPhrase { get; private set; }

public string Message { get; private set; }

public HttpRequestMessage Request { get; private set; }

public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) {
return Task.FromResult(Execute());
}

private HttpResponseMessage Execute() {
var status = Status;
var responseBody = new Models.envelope {
meta = new Models.metadata {
code = (int)status,
type = ReasonPhrase ?? status.ToString().ToCamelCase(),
message = Message
},
data = null
};
var response = Request.CreateResponse(status, responseBody);
response.RequestMessage = Request;
response.ReasonPhrase = ReasonPhrase;
return response;
}
}

并将其设置为 context.Error 属性

if (!string.IsNullOrWhiteSpace(token))
{
var userInfo = await CommunityManager.GetUserInfoAsync(token);
context.Principal = new ArcGISUserPrincipal(userInfo, token);
context.Request.SetUserPrincipal(context.Principal);
}
else
{
context.Error = new ErrorResult(context.Request, "Some message to return");
}

在结果的 Execute 中,您可以将响应消息设置为 JSON 或让内容协商器根据请求 header 确定要返回的媒体类型。

关于c# - 在 Web api Controller 中使用身份验证过滤器发送 json 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42074708/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com