我想为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);
}
}
但我收到错误:Cannot access protected internal method 'ResponseMessage' here
我知道我可以创建自定义基础ApiController并在那里添加该方法,但我想创建扩展方法,以便在其他项目中重用它更容易。
如何从ApiController扩展方法返回IHttpActionResult?
答案 0 :(得分:0)
我设法修复了我的扩展程序。
而不是return apiController.ResponseMessage(response)
我添加了return new ResponseMessageResult(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 Bad Request)如下所示:
{
"error": "error",
"modelState": {
"name": [
"name not valid"
]
},
"error_description": "details"
}