Nice programing

new EmptyResult () 반환 VS NULL 반환

nicepro 2020. 12. 8. 20:02
반응형

new EmptyResult () 반환 VS NULL 반환


ASP.NET MVC에서 내 작업이 내가 사용하는 항목을 반환하지 return new EmptyResult()않거나return null

차이가 있습니까?


반환 할 수 있습니다 null. MVC는이를 감지하고 EmptyResult.

MSDN : EmptyResult 는 null을 반환하는 컨트롤러 작업과 같이 아무것도 수행하지 않는 결과를 나타냅니다.

MVC의 소스 코드.

public class EmptyResult : ActionResult {

    private static readonly EmptyResult _singleton = new EmptyResult();

    internal static EmptyResult Instance {
        get {
            return _singleton;
        }
    }

    public override void ExecuteResult(ControllerContext context) {
    }
}

그리고 ControllerActionInvokernull을 반환하면 MVC가 EmptyResult.

protected virtual ActionResult CreateActionResult(ControllerContext controllerContext, ActionDescriptor actionDescriptor, object actionReturnValue) {
    if (actionReturnValue == null) {
        return new EmptyResult();
    }

    ActionResult actionResult = (actionReturnValue as ActionResult) ??
        new ContentResult { Content = Convert.ToString(actionReturnValue, CultureInfo.InvariantCulture) };
    return actionResult;
}

Codeplex 에서 Asp.Net MVC 프로젝트의 소스 코드를 다운로드 할 수 있습니다 .


null액션에서 돌아올 때 MVC 프레임 워크 (실제로 ControllerActionInvoker클래스)는 내부적으로 새로운 EmptyResult. 따라서 마지막으로 EmptyResult클래스 의 인스턴스가 두 경우 모두 사용됩니다. 따라서 실제 차이가 없습니다.

제 개인적인 의견으로 return new EmptyResult()는 당신의 행동이 아무것도 반환하지 않는다는 것을 더 명확하게 전달하기 때문에 더 좋습니다.


아르투르,

둘 다 기본적으로 http 헤더가 빈 페이지와 함께 다시 전송된다는 점에서 동일합니다. 그러나 원하는 경우 추가로 조정하고 적절한 statusCode 및 statusDescription과 함께 새로운 HttpStatusCodeResult ()를 반환 할 수 있습니다. 즉 :

var result = new HttpStatusCodeResult(999, "this didn't work as planned");
return result;

나는 그것이 유용한 대안이라고 생각합니다.

[편집] -Google 등을 염두에두고이를 활용하는 방법을 보여주는 HttpStatusCodeResult ()의 멋진 구현을 찾았습니다.

http://weblogs.asp.net/gunnarpeipman/archive/2010/07/28/asp-net-mvc-3-using-httpstatuscoderesult.aspx

참고 URL : https://stackoverflow.com/questions/8561038/return-new-emptyresult-vs-return-null

반응형