在.NET核心中从HttpResponseMessage转换为IActionResult

t3psigkw  于 2022-11-19  发布在  .NET
关注(0)|答案(5)|浏览(428)

我正在将以前用.NET Framework编写的一些代码移植到.NET Core。
我有过这样的经历:

HttpResponseMessage result = await client.SendAync(request);
if (result.StatusCode != HttpStatusCode.OK)
{
    IHttpActionResult response = ResponseMessage(result);
    return response;
}

此函数的返回值现在为IActionResult
如何获取HttpResponseMessage result对象并从中返回IActionResult

tnkciper

tnkciper1#

可以使用Ok();BadRequest();等硬集状态代码返回
或者使用动态函数返回

StatusCode(<Your status code number>,<Optional return object>);

这是using Microsoft.AspNetCore.Mvc
下面是StatusCode的详细说明:

/* "this" comes from your class being a subclass of Microsoft.AspNetCore.Mvc.ControllerBase */
StatusCodeResult scr = this.StatusCode(200);
/* OR */
Object myObject = new Object();
ObjectResult ores = this.StatusCode(200, myObject);
return scr; /* or return ores;*/
8xiog9wr

8xiog9wr2#

您应该能够通过使用Microsoft.AspNetCore.Mvc.WebApiCompatShim nuget包将现有代码迁移到ASP.NETCore2.x中。
然后,您可以执行以下操作之一:
1使用ResponseMessageResult

return new ResponseMessageResult(result);

2从ApiController继承您Controller,并保持代码不变:

public class MyController : ApiController 
{
    public IActionResult Get()
    {
        // other code...
        HttpResponseMessage result = await client.SendAync(request);
        if (result.StatusCode != HttpStatusCode.OK)
        {
            IActionResult response = ResponseMessage(result);
            return response;
        }
        // other code...
    }    
}

官方文档中的更多信息

eanckbw9

eanckbw93#

这在.NET v5中要容易得多(erstwhile .NET Core v5)。在Microsoft.AspNetCore.Mvc.CoreDLL中找到的ControllerBase类包含许多方法,这些方法返回从IActionResult继承的对象。IActionResultHttpResponseMessage的替换。我在下面移植了用于返回文件的Web API方法。它基于.NET Framework v4。6.

[HttpGet]
public IHttpActionResult GetFooBar()
{
    var fileContentByteArray = foodBarDomainService.GetExeByteArray();
    var result = new HttpResponseMessage(HttpStatusCode.OK)
    {
        Content = new ByteArrayContent(fileContentByteArray)
    };
    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    {
        FileName = "FooBar.exe"
    };
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    return ResponseMessage(result);
}

下面是我移植到.NET v5的代码:

[HttpGet("GetFooBar", Name = "GetFooBar")]
public IActionResult GetFooBar(string token)
{
    var fileContentByteArray = foodBarDomainService.GetExeByteArray();
    return File(fileContentByteArray, "application/octet-stream", "FooBar.exe");
}

以下是返回实现IActionResult接口以满足特定目的的类的所有方法的完整列表:

public virtual AcceptedResult Accepted(Uri uri, [ActionResultObjectValue] object value);
public virtual AcceptedResult Accepted(string uri, [ActionResultObjectValue] object value);
public virtual AcceptedResult Accepted(Uri uri);
public virtual AcceptedResult Accepted([ActionResultObjectValue] object value);
public virtual AcceptedResult Accepted();
public virtual AcceptedResult Accepted(string uri);
public virtual AcceptedAtActionResult AcceptedAtAction(string actionName, string controllerName, object routeValues, [ActionResultObjectValue] object value);
public virtual AcceptedAtActionResult AcceptedAtAction(string actionName, object routeValues, [ActionResultObjectValue] object value);
public virtual AcceptedAtActionResult AcceptedAtAction(string actionName);
public virtual AcceptedAtActionResult AcceptedAtAction(string actionName, string controllerName);
public virtual AcceptedAtActionResult AcceptedAtAction(string actionName, [ActionResultObjectValue] object value);
public virtual AcceptedAtActionResult AcceptedAtAction(string actionName, string controllerName, [ActionResultObjectValue] object routeValues);
public virtual AcceptedAtRouteResult AcceptedAtRoute(string routeName);
public virtual AcceptedAtRouteResult AcceptedAtRoute(object routeValues, [ActionResultObjectValue] object value);
public virtual AcceptedAtRouteResult AcceptedAtRoute(string routeName, object routeValues, [ActionResultObjectValue] object value);
public virtual AcceptedAtRouteResult AcceptedAtRoute(string routeName, object routeValues);
public virtual AcceptedAtRouteResult AcceptedAtRoute([ActionResultObjectValue] object routeValues);
public virtual BadRequestResult BadRequest();
public virtual BadRequestObjectResult BadRequest([ActionResultObjectValue] object error);
public virtual BadRequestObjectResult BadRequest([ActionResultObjectValue] ModelStateDictionary modelState);
public virtual ChallengeResult Challenge(params string[] authenticationSchemes);
public virtual ChallengeResult Challenge();
public virtual ChallengeResult Challenge(AuthenticationProperties properties);
public virtual ChallengeResult Challenge(AuthenticationProperties properties, params string[] authenticationSchemes);
public virtual ConflictResult Conflict();
public virtual ConflictObjectResult Conflict([ActionResultObjectValue] object error);
public virtual ConflictObjectResult Conflict([ActionResultObjectValue] ModelStateDictionary modelState);
public virtual ContentResult Content(string content);
public virtual ContentResult Content(string content, MediaTypeHeaderValue contentType);
public virtual ContentResult Content(string content, string contentType, Encoding contentEncoding);
public virtual ContentResult Content(string content, string contentType);
public virtual CreatedResult Created(Uri uri, [ActionResultObjectValue] object value);
public virtual CreatedResult Created(string uri, [ActionResultObjectValue] object value);
public virtual CreatedAtActionResult CreatedAtAction(string actionName, string controllerName, object routeValues, [ActionResultObjectValue] object value);
public virtual CreatedAtActionResult CreatedAtAction(string actionName, object routeValues, [ActionResultObjectValue] object value);
public virtual CreatedAtActionResult CreatedAtAction(string actionName, [ActionResultObjectValue] object value);
public virtual CreatedAtRouteResult CreatedAtRoute(object routeValues, [ActionResultObjectValue] object value);
public virtual CreatedAtRouteResult CreatedAtRoute(string routeName, object routeValues, [ActionResultObjectValue] object value);
public virtual CreatedAtRouteResult CreatedAtRoute(string routeName, [ActionResultObjectValue] object value);
public virtual FileStreamResult File(Stream fileStream, string contentType, string fileDownloadName);
public virtual VirtualFileResult File(string virtualPath, string contentType, string fileDownloadName, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag, bool enableRangeProcessing);
public virtual VirtualFileResult File(string virtualPath, string contentType, string fileDownloadName, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag);
public virtual VirtualFileResult File(string virtualPath, string contentType, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag, bool enableRangeProcessing);
public virtual VirtualFileResult File(string virtualPath, string contentType, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag);
public virtual VirtualFileResult File(string virtualPath, string contentType, string fileDownloadName, bool enableRangeProcessing);
public virtual VirtualFileResult File(string virtualPath, string contentType, string fileDownloadName);
public virtual VirtualFileResult File(string virtualPath, string contentType, bool enableRangeProcessing);
public virtual VirtualFileResult File(string virtualPath, string contentType);
public virtual FileStreamResult File(Stream fileStream, string contentType, string fileDownloadName, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag, bool enableRangeProcessing);
public virtual FileStreamResult File(Stream fileStream, string contentType, string fileDownloadName, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag);
public virtual FileStreamResult File(Stream fileStream, string contentType, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag, bool enableRangeProcessing);
public virtual FileStreamResult File(Stream fileStream, string contentType, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag);
public virtual FileStreamResult File(Stream fileStream, string contentType, string fileDownloadName, bool enableRangeProcessing);
public virtual FileStreamResult File(Stream fileStream, string contentType);
public virtual FileContentResult File(byte[] fileContents, string contentType, string fileDownloadName, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag, bool enableRangeProcessing);
public virtual FileContentResult File(byte[] fileContents, string contentType, string fileDownloadName, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag);
public virtual FileContentResult File(byte[] fileContents, string contentType, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag, bool enableRangeProcessing);
public virtual FileContentResult File(byte[] fileContents, string contentType, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag);
public virtual FileContentResult File(byte[] fileContents, string contentType, string fileDownloadName, bool enableRangeProcessing);
public virtual FileContentResult File(byte[] fileContents, string contentType, string fileDownloadName);
public virtual FileContentResult File(byte[] fileContents, string contentType, bool enableRangeProcessing);
public virtual FileContentResult File(byte[] fileContents, string contentType);
public virtual FileStreamResult File(Stream fileStream, string contentType, bool enableRangeProcessing);
public virtual ForbidResult Forbid(params string[] authenticationSchemes);
public virtual ForbidResult Forbid();
public virtual ForbidResult Forbid(AuthenticationProperties properties, params string[] authenticationSchemes);
public virtual ForbidResult Forbid(AuthenticationProperties properties);
public virtual LocalRedirectResult LocalRedirect(string localUrl);
public virtual LocalRedirectResult LocalRedirectPermanent(string localUrl);
public virtual LocalRedirectResult LocalRedirectPermanentPreserveMethod(string localUrl);
public virtual LocalRedirectResult LocalRedirectPreserveMethod(string localUrl);
public virtual NoContentResult NoContent();
public virtual NotFoundObjectResult NotFound([ActionResultObjectValue] object value);
public virtual NotFoundResult NotFound();
public virtual OkResult Ok();
public virtual OkObjectResult Ok([ActionResultObjectValue] object value);
public virtual PhysicalFileResult PhysicalFile(string physicalPath, string contentType, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag);
public virtual PhysicalFileResult PhysicalFile(string physicalPath, string contentType, string fileDownloadName, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag, bool enableRangeProcessing);
public virtual PhysicalFileResult PhysicalFile(string physicalPath, string contentType, string fileDownloadName, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag);
public virtual PhysicalFileResult PhysicalFile(string physicalPath, string contentType, DateTimeOffset? lastModified, EntityTagHeaderValue entityTag, bool enableRangeProcessing);
public virtual PhysicalFileResult PhysicalFile(string physicalPath, string contentType, string fileDownloadName, bool enableRangeProcessing);
public virtual PhysicalFileResult PhysicalFile(string physicalPath, string contentType, string fileDownloadName);
public virtual PhysicalFileResult PhysicalFile(string physicalPath, string contentType, bool enableRangeProcessing);
public virtual PhysicalFileResult PhysicalFile(string physicalPath, string contentType);
public virtual ObjectResult Problem(string detail = null, string instance = null, int? statusCode = null, string title = null, string type = null);
public virtual RedirectResult Redirect(string url);
public virtual RedirectResult RedirectPermanent(string url);
public virtual RedirectResult RedirectPermanentPreserveMethod(string url);
public virtual RedirectResult RedirectPreserveMethod(string url);
public virtual RedirectToActionResult RedirectToAction(string actionName, string controllerName, string fragment);
public virtual RedirectToActionResult RedirectToAction(string actionName, string controllerName, object routeValues);
public virtual RedirectToActionResult RedirectToAction(string actionName, string controllerName, object routeValues, string fragment);
public virtual RedirectToActionResult RedirectToAction(string actionName);
public virtual RedirectToActionResult RedirectToAction(string actionName, object routeValues);
public virtual RedirectToActionResult RedirectToAction();
public virtual RedirectToActionResult RedirectToAction(string actionName, string controllerName);
public virtual RedirectToActionResult RedirectToActionPermanent(string actionName, string controllerName, object routeValues, string fragment);
public virtual RedirectToActionResult RedirectToActionPermanent(string actionName, string controllerName, object routeValues);
public virtual RedirectToActionResult RedirectToActionPermanent(string actionName, string controllerName, string fragment);
public virtual RedirectToActionResult RedirectToActionPermanent(string actionName, string controllerName);
public virtual RedirectToActionResult RedirectToActionPermanent(string actionName, object routeValues);
public virtual RedirectToActionResult RedirectToActionPermanent(string actionName);
public virtual RedirectToActionResult RedirectToActionPermanentPreserveMethod(string actionName = null, string controllerName = null, object routeValues = null, string fragment = null);
public virtual RedirectToActionResult RedirectToActionPreserveMethod(string actionName = null, string controllerName = null, object routeValues = null, string fragment = null);
public virtual RedirectToPageResult RedirectToPage(string pageName);
public virtual RedirectToPageResult RedirectToPage(string pageName, string pageHandler, object routeValues, string fragment);
public virtual RedirectToPageResult RedirectToPage(string pageName, string pageHandler, string fragment);
public virtual RedirectToPageResult RedirectToPage(string pageName, string pageHandler, object routeValues);
public virtual RedirectToPageResult RedirectToPage(string pageName, string pageHandler);
public virtual RedirectToPageResult RedirectToPage(string pageName, object routeValues);
public virtual RedirectToPageResult RedirectToPagePermanent(string pageName, string pageHandler, string fragment);
public virtual RedirectToPageResult RedirectToPagePermanent(string pageName);
public virtual RedirectToPageResult RedirectToPagePermanent(string pageName, object routeValues);
public virtual RedirectToPageResult RedirectToPagePermanent(string pageName, string pageHandler);
public virtual RedirectToPageResult RedirectToPagePermanent(string pageName, string pageHandler, object routeValues, string fragment);
public virtual RedirectToPageResult RedirectToPagePermanentPreserveMethod(string pageName, string pageHandler = null, object routeValues = null, string fragment = null);
public virtual RedirectToPageResult RedirectToPagePreserveMethod(string pageName, string pageHandler = null, object routeValues = null, string fragment = null);
public virtual RedirectToRouteResult RedirectToRoute(string routeName);
public virtual RedirectToRouteResult RedirectToRoute(string routeName, object routeValues);
public virtual RedirectToRouteResult RedirectToRoute(string routeName, string fragment);
public virtual RedirectToRouteResult RedirectToRoute(string routeName, object routeValues, string fragment);
public virtual RedirectToRouteResult RedirectToRoute(object routeValues);
public virtual RedirectToRouteResult RedirectToRoutePermanent(string routeName, string fragment);
public virtual RedirectToRouteResult RedirectToRoutePermanent(string routeName, object routeValues);
public virtual RedirectToRouteResult RedirectToRoutePermanent(string routeName, object routeValues, string fragment);
public virtual RedirectToRouteResult RedirectToRoutePermanent(string routeName);
public virtual RedirectToRouteResult RedirectToRoutePermanent(object routeValues);
public virtual RedirectToRouteResult RedirectToRoutePermanentPreserveMethod(string routeName = null, object routeValues = null, string fragment = null);
public virtual RedirectToRouteResult RedirectToRoutePreserveMethod(string routeName = null, object routeValues = null, string fragment = null);
public virtual SignInResult SignIn(ClaimsPrincipal principal, string authenticationScheme);
public virtual SignInResult SignIn(ClaimsPrincipal principal, AuthenticationProperties properties);
public virtual SignInResult SignIn(ClaimsPrincipal principal, AuthenticationProperties properties, string authenticationScheme);
public virtual SignInResult SignIn(ClaimsPrincipal principal);
public virtual SignOutResult SignOut();
public virtual SignOutResult SignOut(AuthenticationProperties properties);
public virtual SignOutResult SignOut(params string[] authenticationSchemes);
public virtual SignOutResult SignOut(AuthenticationProperties properties, params string[] authenticationSchemes);
public virtual StatusCodeResult StatusCode([ActionResultStatusCode] int statusCode);
kkbh8khc

kkbh8khc4#

谢谢大家的回答。我走了一条稍微不同的路线。我猜这段代码的意义在于,如果SendAsync以任何方式失败,我都希望返回该错误消息。因此,我将其改为如下所示:

if (result.StatusCode != HttpStatusCode.OK)
{
    return BadRequest(result.ReasonPhrase);
}
xoefb8l8

xoefb8l85#

这对我很有效....Net Core 6.0

public async Task<IActionResult> GetAll(string catalogname,[FromQuery] GetAllQuery query)
    {
        String hardCodedJson = "{\"Id\":\"123\",\"DateOfRegistration\":\"2012-10-21T00:00:00+05:30\",\"Status\":0}";

        return Content(hardCodedJson , "application/json");
    }

相关问题