在 webApi2 中,我可以通过继承 IHttpActionResult 编写自定义 ActionResult.
In webApi2 i could write a custom ActionResult by inheriting IHttpActionResult.
示例:
public class MenivaActionResult : IHttpActionResult { private readonly HttpRequestMessage _request; private readonly ServiceResponseBase _response; public MenivaActionResult(HttpRequestMessage request, ServiceResponseBase response) { _request = request; _response = response; } public Task<HttpResponseMessage> ExecuteAsync(CancellationToken token) { HttpResponseMessage httpresponseMessage = _response.Exception != null ? _request.CreateErrorResponse((HttpStatusCode)_response.HttpCode, _response.Exception.Message+":"+_response.Exception.HelpCode) : _request.CreateResponse((HttpStatusCode)_response.HttpCode, _response.Data); return Task.FromResult(httpresponseMessage); } }ServiceResponseBase 类对象包含来自服务层的所有异常和数据..
The ServiceResponseBase class object holds all the exception and data from service layer..
我如何将此代码移植到 asp 核心.我试过了,但我不知道如何从 核心中的 HttpRequestMessage 对象创建响应消息.IActionResult 只有 Task ExecuteResultAsync(ActionContext context) 方法.我如何修改此方法的响应
How i can port this code to asp core. I tried but i dont know how create a response message from HttpRequestMessage object in core. The IActionResult only have Task ExecuteResultAsync(ActionContext context) method. how i can modify the response from this method
推荐答案这是一个例子:
public class TestResult { public Exception Exception { get; set; } public object Data { get; set; } } public class TestActionResult : IActionResult { private readonly TestResult _result; public TestActionResult(TestResult result) { _result = result; } public async Task ExecuteResultAsync(ActionContext context) { var objectResult = new ObjectResult(_result.Exception ?? _result.Data) { StatusCode = _result.Exception != null ? StatusCodes.Status500InternalServerError : StatusCodes.Status200OK }; await objectResult.ExecuteResultAsync(context); } }ObjectResult 是如果您从操作返回非IActionResult 的结果将被转换的类型.它将为您进行内容协商.
ObjectResult is the type your results are converted if you return a non-IActionResult from an action. It will do content negotiation for you.
您也可以从 ObjectResult 继承并设置要写入构造函数的状态代码和数据.
You could also inherit from ObjectResult and setup the status code and data to be written in the constructor.
有关 ASP.NET Core 内容协商的更多信息:docs.microsoft/en-us/aspnet/core/mvc/models/formatting#content-negotiation
More on content negotiation in ASP.NET Core: docs.microsoft/en-us/aspnet/core/mvc/models/formatting#content-negotiation
更多推荐
如何在asp.net core中编写自定义actionResult
发布评论