Ran*_*iff 3 http-status-codes http-status-code-400 asp.net-core asp.net-core-webapi
是否可以从 Asp.Net Core 3.1 Web Api 返回自定义错误消息给客户端?我尝试了几种不同的方法来设置“ReasonPhrase”,但没有成功。我尝试过使用StatusCode:
return StatusCode(406, "Employee already exists");
Run Code Online (Sandbox Code Playgroud)
我尝试使用 HttpResponseMessage 返回:
HttpResponseMessage msg = new HttpResponseMessage();
msg.StatusCode = HttpStatusCode.NotAcceptable;
msg.ReasonPhrase = "Employee alredy exists";
return (IActionResult)msg;
Run Code Online (Sandbox Code Playgroud)
我试图向客户端返回一条消息,调用该员工已存在的方法:
public async Task<IActionResult> CreateEmployee([FromBody] EmployeeImport Employee)
{
var exists = await employeeService.CheckForExistingEmployee(Employee);
if (exists > 0)
{
//return StatusCode(406, "Employee already exists");
HttpResponseMessage msg = new HttpResponseMessage();
msg.StatusCode = HttpStatusCode.NotAcceptable;
msg.ReasonPhrase = "Employee already exists";
return (IActionResult)msg;
}
}
Run Code Online (Sandbox Code Playgroud)
这是客户端中的代码:
public async Task<ActionResult>AddEmployee(EmployeeImport employee)
{
var message = await CommonClient.AddEmployee(employee);
return Json(message.ReasonPhrase, JsonRequestBehavior.AllowGet);
}
public async Task<HttpResponseMessage> AddEmployee(EmployeeImport employee)
{
var param = Newtonsoft.Json.JsonConvert.SerializeObject(employee);
HttpContent contentPost = new StringContent(param, System.Text.Encoding.UTF8, "application/json");
var response = await PerformPostAsync("entity/NewEmployee", contentPost);
return response;
}
protected async Task<HttpResponseMessage> PerformPostAsync(string requestUri, HttpContent c)
{
_webApiClient = new HttpClient { BaseAddress = _baseAddress };
_webApiClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken);
var webApiResponse = await _webApiClient.PostAsync(requestUri, c);
return webApiResponse;
}
Run Code Online (Sandbox Code Playgroud)
为此,您可以创建一个实现该IActionResult接口的自定义错误类,如下所示:
public class CustomError : IActionResult
{
private readonly HttpStatusCode _status;
private readonly string _errorMessage;
public CustomError(HttpStatusCode status, string errorMessage)
{
_status = status;
_errorMessage = errorMessage;
}
public async Task ExecuteResultAsync(ActionContext context)
{
var objectResult = new ObjectResult(new
{
errorMessage = _errorMessage
})
{
StatusCode = (int)_status,
};
context.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = _errorMessage;
await objectResult.ExecuteResultAsync(context);
}
}
Run Code Online (Sandbox Code Playgroud)
并使用以下形式:
[HttpGet]
public IActionResult GetEmployee()
{
return new CustomError(HttpStatusCode.NotFound, "The employee was not found");
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4056 次 |
| 最近记录: |