如果我尝试从Page.aspx重定向页面,则会出现问题

时间:2018-11-12 16:23:56

标签: c# asp.net redirect

我正在构建一个ASP.NET应用程序。

此页面为Pagina.aspx,这是代码:

Public Sub ConfigureAuth(app As IAppBuilder)
    app.CreatePerOwinContext(AddressOf ApplicationDbContext.Create)
    app.CreatePerOwinContext(Of ApplicationUserManager)(AddressOf ApplicationUserManager.Create)
    app.CreatePerOwinContext(Of ApplicationSignInManager)(AddressOf ApplicationSignInManager.Create)
   app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType)
    app.UseCookieAuthentication(New CookieAuthenticationOptions() With {
        .AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        .Provider = New CookieAuthenticationProvider() With {
            .OnValidateIdentity = SecurityStampValidator.OnValidateIdentity(Of ApplicationUserManager, ApplicationUser)(
                validateInterval:=TimeSpan.FromMinutes(30),
                regenerateIdentity:=Function(manager, user) user.GenerateUserIdentityAsync(manager))},
        .LoginPath = New PathString("/Account/Login")})
    app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie)

    Dim facebookOptions = New FacebookAuthenticationOptions With {
        .AppId = ConfigurationManager.AppSettings("FacebookClientID"),
        .AppSecret = ConfigurationManager.AppSettings("FacebookClientSecret"),
        .Provider = New FacebookAuthenticationProvider With {
            .OnAuthenticated = Function(context)
                                   context.Identity.AddClaim(New Claim("Provider", "Facebook"))
                                   context.Identity.AddClaim(New Claim("provider:name", context.Identity.FindFirstValue(ClaimTypes.Name)))
                                   context.Identity.AddClaim(New Claim("provider:accesstoken", context.AccessToken, ClaimValueTypes.String, "Facebook"))
                                   context.Identity.AddClaim(New Claim("provider:picture", String.Format("//graph.facebook.com/{0}/picture?type=square", context.User.Value(Of String)("id"))))
                                   Dim email = context.Identity.FindFirstValue(ClaimTypes.Email)
                                   If email IsNot Nothing Then
                                       context.Identity.AddClaim(New Claim("provider:email", email))
                                   Else
                                       Dim fb = New Facebook.FacebookClient(context.AccessToken)
                                       Dim myInfo = fb.Get("/me?fields=email")
                                       email = myInfo("email")
                                       If email IsNot Nothing Then
                                           context.Identity.AddClaim(New Claim("provider:email", email))
                                       Else
                                           Throw New ArgumentNullException("myInfo.Email")
                                       End If
                                   End If

                                   Return Task.FromResult(0)
                               End Function}}
    facebookOptions.Scope.Add("email")
    app.UseFacebookAuthentication(facebookOptions)

    app.UseGoogleAuthentication(New GoogleOAuth2AuthenticationOptions() With {
       .ClientId = ConfigurationManager.AppSettings("GoogleClientID"),
       .ClientSecret = ConfigurationManager.AppSettings("GoogleClientSecret"),
       .Provider = New GoogleOAuth2AuthenticationProvider With {.OnAuthenticated = Function(context)
                                                                                       context.Identity.AddClaim(New Claim("Provider", "Google"))
                                                                                       context.Identity.AddClaim(New Claim("provider:name", context.Identity.FindFirstValue(ClaimTypes.Name)))
                                                                                       context.Identity.AddClaim(New Claim("provider:email", context.Identity.FindFirstValue(ClaimTypes.Email)))
                                                                                       context.Identity.AddClaim(New Claim("provider:accesstoken", context.AccessToken, ClaimValueTypes.String, "Google"))
                                                                                       context.Identity.AddClaim(New Claim("provider:picture", context.User.SelectToken("image")?.Value(Of String)("url")))

                                                                                       Return Task.FromResult(0)
                                                                                   End Function}})

    app.UseLinkedInAuthentication(New LinkedInAuthenticationOptions With {
        .ClientId = ConfigurationManager.AppSettings("LinkedInClientID"),
        .ClientSecret = ConfigurationManager.AppSettings("LinkedInClientSecret"),
        .Provider = New LinkedInAuthenticationProvider With {.OnAuthenticated = Function(context)
                                                                                    context.Identity.AddClaim(New Claim("Provider", "LinkedIn"))
                                                                                    context.Identity.AddClaim(New Claim("provider:name", context.Name))
                                                                                    context.Identity.AddClaim(New Claim("provider:email", context.Email))
                                                                                    context.Identity.AddClaim(New Claim("provider:accesstoken", context.AccessToken, ClaimValueTypes.String, "LinkedIn"))
                                                                                    context.Identity.AddClaim(New Claim("provider:picture", context.User.SelectToken("pictureUrl").ToString))

                                                                                    Return Task.FromResult(0)
                                                                                End Function}})

    Dim oktaOptions = New OpenIdConnect.OpenIdConnectAuthenticationOptions With {
        .AuthenticationType = "okta",
        .SignInAsAuthenticationType = "Cookies",
        .Authority = ConfigurationManager.AppSettings("okta:Authority"),
        .ResponseType = Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectResponseType.CodeIdToken,
        .ClientId = ConfigurationManager.AppSettings("okta:ClientId"),
        .ClientSecret = ConfigurationManager.AppSettings("okta:ClientSecret"),
        .RedirectUri = ConfigurationManager.AppSettings("okta:RedirectUri"),
        .TokenValidationParameters = New Microsoft.IdentityModel.Tokens.TokenValidationParameters With {.ValidateIssuer = True},
        .Scope = "openid profile email"
    }
    app.UseOpenIdConnectAuthentication(oktaOptions)


    Dim auth0Options = New OpenIdConnect.OpenIdConnectAuthenticationOptions With {
        .AuthenticationType = "auth0",
        .SignInAsAuthenticationType = "Cookies",
        .Authority = ConfigurationManager.AppSettings("auth0:Authority"),
        .ResponseType = Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectResponseType.CodeIdToken,
        .ClientId = ConfigurationManager.AppSettings("auth0:ClientId"),
        .ClientSecret = ConfigurationManager.AppSettings("auth0:ClientSecret"),
        .RedirectUri = ConfigurationManager.AppSettings("auth0:RedirectUri"),
        .TokenValidationParameters = New Microsoft.IdentityModel.Tokens.TokenValidationParameters With {.ValidateIssuer = True},
        .Scope = "openid profile email"
    }
    app.UseOpenIdConnectAuthentication(auth0Options)

    app.MapSignalR

    GlobalHost.DependencyResolver.Register(GetType(IUserIdProvider), Function() New MySignalRIdProvider())
End Sub

我使用以下网址调用此页面:

namespace AnalisiHRVElaborazioni
{
    public partial class Pagina : System.Web.UI.Page
    {
        OmniaCareRehabDemProductionEntities dbTool = new OmniaCareRehabDemProductionEntities();

        static HttpClient client = new HttpClient();

        protected void Page_Load(object sender, EventArgs e)
        {
            int? locateInput = null;
            int? replaceMethod = null;
            int? replaceInput = null;
            int? detrendMethod = null;
            int? waveletLevels = null;
            int? smoothMethod = null;
            int? smoothSpan = null;
            double? smoothDegree = null;
            int? polyOrder = null;
            int? meanCorrection = null;
            int? resampleRate = null;
            int? lambda = null;
            int? sdnni = null;
            int? pnnx = null;
            int? tFWindow = null;
            int? tFOverlap = null;
            int? m = null;
            double? r = null;
            int? n1 = null;
            int? n2 = null;
            int? breakpoint = null;
            double vlfMin;
            double vlfMax;
            double lfMin;
            double lfMax;
            double hfMin;
            double hfMax;

            int? arOptionOrder = null;
            int? winWith = null;
            int? winOverlap = null;
            int? pointPSD = null;
            int? interpolationRate = null;

            String idSlot = Request.QueryString["idSlot"];
            if (!String.IsNullOrEmpty(idSlot))
            {
                Response.Redirect("Home/TimeDomain");
            }
            else
            {
                String charMethod = Request.QueryString["charMethod"];
                String _locateInput = Request.QueryString["locateInput"];

                String _replaceMethod = Request.QueryString["replaceMethod"];
                String _replaceInput = Request.QueryString["replaceInput"];
                String _detrendMethod = Request.QueryString["detrendMethod"];
                String _waveletLevels = Request.QueryString["waveletLevels"];

                if (!String.IsNullOrEmpty(_locateInput))
                    locateInput = int.Parse(_locateInput);

                if (!String.IsNullOrEmpty(_replaceMethod))
                    replaceMethod = int.Parse(_replaceMethod);

                if (!String.IsNullOrEmpty(_replaceInput))
                    replaceInput = int.Parse(_replaceInput);

                if (!String.IsNullOrEmpty(_detrendMethod))
                    detrendMethod = int.Parse(_detrendMethod);

                if (!String.IsNullOrEmpty(_waveletLevels))
                    waveletLevels = int.Parse(_waveletLevels);


                RR rr = new RR();
                RR.Filter filter = new RR.Filter();
                filter.locateInput = locateInput;
                filter.replaceMethod = replaceMethod;
                filter.replaceInput = replaceInput;
                filter.detrendMethod = detrendMethod;
                filter.waveletLevels = waveletLevels;

                //recupero l'RR
                rr.rr = getRR(10);
                rr.filter = filter;

                var json = new JavaScriptSerializer().Serialize(rr);

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:28302/api/parse");
                request.Method = "POST";
                System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
                Byte[] byteArray = encoding.GetBytes(json);

                request.ContentLength = byteArray.Length;
                request.ContentType = @"application/json";

                using (Stream dataStream = request.GetRequestStream())
                {
                    dataStream.Write(byteArray, 0, byteArray.Length);
                }
                long length = 0;
                try
                {
                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    {
                        length = response.ContentLength;
                        Stream stream = response.GetResponseStream();
                        StreamReader sr = new StreamReader(stream);
                        var jsonObject = new JavaScriptSerializer().DeserializeObject(sr.ReadToEnd());
                        //ottenuto l oggetto posso mettere tutto in sessione
                        Session["jsonElaborato"] = jsonObject;
                        Session["loadJson"] = true;
                        Response.Redirect("Home/TimeDomain/?idSlot=null");
                    }
                }
                catch (WebException ex)
                {
                    // Log exception and throw as for GET example above
                }                 
            }
        }   

        [NonAction]
        public decimal?[] getRR(int idSlot)
        {
            /**
             * qui devo recuperare il codice per recuperare le informazioni real time dal database
             * */
            return (from r in dbTool.AA_V_RRSlotXRR
                    where r.IdSlotRR == idSlot
                    select r.y).ToArray();

        }  
    }
}

如果我尝试调用此页面。我可以执行所有代码并调用Web服务。

然后在执行这些代码行之后

http://localhost:12636/Pagina.aspx/?charMethod="percent"&locateInput=900.....

我希望系统在Session["jsonElaborato"] = jsonObject; Session["loadJson"] = true; Response.Redirect("Home/TimeDomain/?idSlot=null"); 页上重定向浏览器。但是不幸的是,页面总是在Home/TimeDomain页面中重定向。为什么?

2 个答案:

答案 0 :(得分:1)

请尝试以下操作:

try
{

  // your coding here

}
catch(){}
 Response.Redirect("Home/TimeDomain/?idSlot=null");

答案 1 :(得分:0)

不是很干净,但是可能您需要类似的东西

Response.Redirect("~/TimeDomain/?idSlot=null", false)