工作正常:
context.Result = new ForbidResult();
但是我想通过这样的消息传递“禁止” :
context.Result = new ForbidResult("Forbidden");
.net core 2 Web API中的。但是当我在这段代码上面编写这段代码时,我得到了
500内部服务器错误
因此,任何人都可以帮助我如何执行上面的代码行。
示例代码
public class ClaimRequirementFilter : Microsoft.AspNetCore.Mvc.Filters.IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext context)
{
// working code
context.Result = new ForbidResult();
// Code with error (500 Internal Server Error)
context.Result = new ForbidResult("Forbidden");
}
}
答案 0 :(得分:4)
我创建了这两个类(1. CustomError和2. CustomUnauthorizedResult),并使用这两个类来处理Authorization。您可以在此处传递动态消息和状态代码。
public class CustomError
{
public string Error { get; }
public CustomError(string message)
{
Error = message;
}
}
public class CustomUnauthorizedResult : JsonResult
{
public CustomUnauthorizedResult(string message, int statusCode) : base(new CustomError(message))
{
StatusCode = statusCode;
}
}
public class ClaimRequirementFilter : Microsoft.AspNetCore.Mvc.Filters.IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext context)
{
context.Result = new CustomUnauthorizedResult("Authorization failed.", statusCode:403);
}
}
答案 1 :(得分:2)
您可以简单地使用 ObjectResult 返回带有状态代码的自定义响应。
查看语法,
return new ObjectResult("Message") {StatusCode = YOUR_STATUS_CODE };
示例:
public async Task<IActionResult> Post([FromBody] SomeData _data)
{
// do your stuff
// return forbidden with custom message
return new ObjectResult("Forbidden") { StatusCode = 403};
}