gpt4 book ai didi

c# - ApiController 扩展方法 - 无法访问 ResponseMessage

转载 作者:行者123 更新时间:2023-11-30 12:56:23 25 4
gpt4 key购买 nike

我想为 ApiController 创建扩展方法,以便能够返回自定义内容。
我的想法是用我自己的详细信息返回自定义错误。我想返回类似于 OAuthAuthorizationServerProvider 返回的错误的自定义错误:

{
"error": "invalid_grant",
"error_description": "You have 3 more attempts before Your account will be locked."
}

在我的 ApiController 中,我添加了这个方法:

public IHttpActionResult Test()
{
HttpError err = new HttpError();
err["error"] = "40001";
err["error_description"] = "Something is wrong";
var response = Request.CreateErrorResponse(HttpStatusCode.NotFound, err);
return ResponseMessage(response);
}

这给了我漂亮的回复:

{
"error": "40001",
"error_description": "Somethis is wrong"
}

我尝试将其转换为以下扩展方法:

public static class ApiControllerExtensions
{
public static IHttpActionResult BadRequest(this ApiController apiController, string error, string errorDetails)
{
HttpError err = new HttpError();
err["error"] = error;
err["error_description"] = errorDetails;
var response = apiController.Request.CreateErrorResponse(HttpStatusCode.NotFound, err);
return apiController.ResponseMessage(response);
}
}

但我收到错误:无法在此处访问 protected 内部方法“ResponseMessage”

我知道我可以创建自定义基础 ApiController 并在其中添加该方法,但我想创建扩展方法以便在其他项目中更容易重用它。

如何从 ApiController 扩展方法返回 IHttpActionResult?

最佳答案

我已经设法修复我的扩展方法。
我添加了 return new ResponseMessageResult(response) 而不是 return apiController.ResponseMessage(response)

下面是有效的扩展方法:

public static class ApiControllerExtensions
{
public static IHttpActionResult InvalidRequest(this ApiController apiController, string error, string errorDetails = "", ModelStateDictionary modelState = null)
{
var err = modelState != null ? new HttpError(modelState, false) : new HttpError();
if (err.ContainsKey("message"))
err.Remove("message");
err["error"] = error;
if (!string.IsNullOrWhiteSpace(errorDetails))
err["error_description"] = errorDetails;
var response = apiController.Request.CreateErrorResponse(HttpStatusCode.BadRequest, err);

return new ResponseMessageResult(response);
}

public static IHttpActionResult InvalidRequest(this ApiController apiController, string error, ModelStateDictionary modelState = null)
{
return InvalidRequest(apiController, error, null, modelState);
}
}

示例用法如下所示:

return this.InvalidRequest("error")

return this.InvalidRequest("error","error details")

var msd = new ModelStateDictionary();
msd.AddModelError("name", "name not valid");

return this.InvalidRequest("error",msd);
return this.InvalidRequest("error","details",msd);

返回的 JSON(400 错误请求)如下所示:

{
"error": "error",
"modelState": {
"name": [
"name not valid"
]
},
"error_description": "details"
}

关于c# - ApiController 扩展方法 - 无法访问 ResponseMessage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41481246/

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