Ajax 통화에서 웹 서비스에서 로그인 페이지로 리디렉션하는 방법은 무엇입니까?

StackOverflow https://stackoverflow.com/questions/610699

문제

jQuery를 사용하여 웹 서비스 (*.AMSX) 메소드를 호출하고 있습니다. 웹 서비스는 Formsauthentication을 사용하여 호출 사용자가 인증되었는지 여부를 결정합니다. 웹 메소드에서 리디렉션 상태 코드를 반환 할 수 없습니다.

[WebMethod(EnableSession=true)]
public Dictionary<string, object> GetArchivedFiles(int pageSize, int page)
{
    if(HttpContext.Current.User.Identity.IsAuthenticated && Session["UserId"] != null)
        // Do some computing and return a Dictionary.       

    // Method will fall through here if the user is not authenticated.
    HttpContext.Current.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
    return null;
}

리디렉션이 작동하지 않으며이 작업을 수행 할 때 항상 500 개의 내부 서버 오류가 발생합니다. 다른 코드를 시도했습니다. 여기로가는 권장 방법은 무엇입니까? JavaScript에서 리디렉션 정보를 읽고 새 페이지를로드해야합니다 (또는 로그인 제어 AJAX Way를 표시 할 수도 있음).

실제로 JSON 객체를 다시 얻습니다.

{"Message":"Authentication failed.","StackTrace":null,"ExceptionType":"System.InvalidOperationException"
}

디버거를 실행하려고 시도했지만 모든 방법이 입력되었음을 보여주지 않습니다. 보시다시피 스택 트레이스는 무효입니다 ...

Fiddler에서 표준 게시물 요청 (xmlhttprequest 아님)으로 호출하면 실제로 예외가 반환됩니다.

HTTP/1.1 500 Internal Server Error
Server: ASP.NET Development Server/9.0.0.0
Date: Wed, 04 Mar 2009 14:46:02 GMT
X-AspNet-Version: 2.0.50727
Cache-Control: private
Content-Type: text/plain; charset=utf-8
Content-Length: 1739
Connection: Close

System.NotSupportedException: The type System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] is not supported because it implements IDictionary.
   at System.Xml.Serialization.TypeScope.GetDefaultIndexer(Type type, String memberInfo)
   at System.Xml.Serialization.TypeScope.ImportTypeDesc(Type type, MemberInfo memberInfo, Boolean directReference)
   at System.Xml.Serialization.TypeScope.GetTypeDesc(Type type, MemberInfo source, Boolean directReference, Boolean throwOnError)
   at System.Xml.Serialization.ModelScope.GetTypeModel(Type type, Boolean directReference)
   at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(Type type, XmlRootAttribute root, String defaultNamespace)
   at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(Type type, XmlRootAttribute root)
   at System.Web.Services.Protocols.XmlReturn.GetInitializers(LogicalMethodInfo[] methodInfos)
   at System.Web.Services.Protocols.XmlReturnWriter.GetInitializers(LogicalMethodInfo[] methodInfos)
   at System.Web.Services.Protocols.MimeFormatter.GetInitializers(Type type, LogicalMethodInfo[] methodInfos)
   at System.Web.Services.Protocols.HttpServerType..ctor(Type type)
   at System.Web.Services.Protocols.HttpServerProtocol.Initialize()
   at System.Web.Services.Protocols.ServerProtocol.SetContext(Type type, HttpContext context, HttpRequest request, HttpResponse response)
   at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing)
도움이 되었습니까?

해결책 3

내가 한 일은 상태 코드를 전혀 없애고 반환하는 것이 었습니다. null. 메소드는 총 페이지가 0 인 경우 파일이없는 경우 빈 목록을 반환합니다. 그러나 사용자가 인증되지 않으면 반환됩니다. null, 그러한 경우에 사용합니다 window.location 브라우저를 로그인 페이지로 리디렉션합니다.

다른 팁

웹 서비스에서 리디렉션해서는 안됩니다. 리디렉션 해야하는지 여부를 표시하려면 값을 반환해야합니다 (이것은 분리 될 수 있습니다 Authenticate 반환하는 방법 a string, null이라면, 그것은 그것이 인증되었음을 의미합니다. 그렇지 않은 경우 리디렉션 URL이 포함됩니다.) 그런 다음 JavaScript에서는 반환 값을 확인하고 설정하여 적절하게 리디렉션 할 수 있습니다. window.location 재산.

그건 그렇고, 웹 서비스에 대한 액세스에 인증이 필요하지 않아야합니다.

나는 ASP.NET과 특별히 경험이 없지만 일반적으로 "성공", "내용", "errortype"와 같은 속성이있는 ajaxResponse 객체를 사용하는 것을 좋아합니다. 이 경우 로그인이 필요한 응답은 "false"및 errortype "로그인"또는 선택한 모든 것이 성공할 수 있습니다. JavaScript 코드는 이러한 속성을 기반으로 반환 된 객체를 처리하는 방법을 결정하여 사용자에게 로그인 양식을 표시하거나 새 페이지로 리디렉션합니다.

웹 서비스에서 예외를 던지십시오. 발신자에서 이것을 잡고 필요에 따라 리디렉션하십시오.

실제로, 웹 서비스 (ajax 또는 not)에 대한 게시물에 "value value value"application/json; charset = utf-8 "이 포함 된 경우 ASMX 스택은 JSON 형식의 문자열을 상태 코드 401 (무단)을 포함하여 일반적으로 예상되는 것으로 추정되는 리디렉션을 제외하고, 콘텐츠 유형 헤더를 보내지 않으면 상태 코드 OK 및 AJAX를 사용하여 응답으로 로그인 페이지에 브라우저 리디렉션을 얻을 수 있습니다. 로그인 페이지 html을 응답으로 얻을 수 있습니다.

이것이 명확하게하는 데 도움이되기를 바랍니다.

문안 인사

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top