Redirect of extension methods

Source: Internet
Author: User

Preface:

When I look at the title, many of my friends may not know what I want to write. Writing this articleArticleI struggled with myself for a long time. Should I write this article? After all, from the perspective of realism, this article may fall into the ranks of "nonsense", because for most of my friends, all of the following extension methods may not be used.

If this is the case, let's look at it as an "infinite" idea. If you don't want to waste your precious time, click here.RedirectGo back to the blog homepage.

 

Why does a redirect consume the pen and ink of an article?

I guess I won't be the first to write the Redirect statement, but if the extension method + redirect is used, I may be the first person.

 

What medicines are sold in Huludao?

The effect of this "Boundless" idea is:

If the page is foo. aspx,

      • PassThis. View <Foo> ()To redirect;
      • PassThis. url <Foo> ()To obtain the URL;
      • PassThis. url <Foo> (New {param1 = "value1", param2 = "value2 "});To return the URL with parameters.

 

The idea source of "Infinite margin:

ASP. net mvc is the main source of this idea. All the friends who have learned ASP. net mvc are familiar with how controller knows the returned page. The main method is as follows:

 
PublicActionresultIndex (){ReturnView ();ReturnView ("Viewname");ReturnView ("Viewname",New{Returnurl ="Foo"});ReturnRedirecttoaction ("Actionname");}

 

Do not understand ASP. net MVC friends do not matter, because this article is actually with ASP. net MVC does not matter at all. It has nothing to do with the view Extension Method of webform later. It is only the same method name.

 

How to implement it?

For the simplest case: the page is in the root directory, directly accordingClass Name + ". aspx"Return.

Public static stringURL <t> (ThisIhttphandlerHttphandler ){Return string. Format ("~ /{0}. aspx",Typeof(T). Name );}

 

However, for multi-level directories:

How can we return the desired page url Based on the type? So we have to make some changes. How can this problem be solved? The namespace is also pulled up:

For example, the namespace in the background of the index. ASPX page in the home folder is redirecttests. Views. Home, which is assembled Based on the namespace and class name "~ /Views/home/index. aspx "is not easy yet.

ExampleCode:

Public static stringURL <tview> (ThisIhttphandlerHttphandler ){StringFullviewname =Typeof(Tview). fullname;String[] Splits = fullviewname. Split ('.');If(Splits. Length <2)Throw newArgumentexception("Cannot find the namespace on view name");Return string. Format ("~ /Views/{0}/{1}. aspx", Splits [splits. Length-2], splits [splits. Length-1]);}

 

The code above limits the path only in the Views folder. If you are interested, you may wish to modify it.

 

How do I add a query string to a URL?

What? This is also a problem? I have seen many friends write query strings as follows:

 
StringUrl ="~ /Foo. aspx? Param1 ="+ Value1 +"& Param2 ="+ Value2 ...;
 
 

Or, if you want to write beautiful words, write the following:

 
StringUrl =String. Format ("~ /Foo. aspx? Param1 = {0} & param2 = {1 }", Value1, value2 );

 

When the query string is long, it may be messy. I personally think that ASP. NET MVC is a good way to write, which leads to another "Boundless" idea. Please refer to the following statement:

 
This. Url <Foo> (New{Param1 ="Value1", Param2 ="Value2"});

Of course, the execution efficiency is definitely a little lower, because reflection is used (in other words, you don't have to worry about "shooting ".Fast reflection).

 

Public static stringURL <tview> (ThisIhttphandlerHttphandler,ObjectParam ){StringQuerystring = Param. toquerystring ();StringVirtualpath =String. Format ("{0 }? {1 }", Httphandler. url <tview> (), querystring );ReturnVirtualpath ;}

 
 
 /// <Summary> ///  Assemble query strings  /// </Summary> /// <typeparam name = "T"> </typeparam> /// <Param name = "model"> </param> /// <returns> </returns> Public static string Toquerystring <t> ( This T model ){ Stringbuilder SB = New  Stringbuilder (); If (Model! = Null ){ Type Type = model. GetType (); // Traverse all attributes and assemble query strings Type. getproperties (). foreach (P => {sb. append (P. Name); sb. append ( "=" ); Sb. append (urlencode (P. getvalue (model,Null ); Sb. append ( "&" );}); If (Sb. length> 0 ){ // Remove the last "&"  Return SB. tostring (0, SB. Length-1 );}} Return SB. tostring ();} /// <Summary> ///  URL Encoding  /// </Summary> /// <Param name = "OBJ"> </param> /// <returns> </returns>  Public static string Urlencode ( Object OBJ ){If (OBJ = Null ){ Return string . Empty ;} Else if (OBJ Is  Datetime ){ String Value = (( Datetime ) OBJ). tostring ( "Yyyy-mm-dd hh: mm: Ss. ffffff" ); Return System. Web. Httputility . Urlencode (value );} Return System. Web.Httputility . Urlencode (obj. tostring ());}

 

For the URL encoding section of the Code above, you can see that if it is a string of the datetime type, the specific format is converted here. If it is not converted in this way, when obtaining the datetime type, it cannot be guaranteed that the string can be converted back to the correct datetime type.

With the above introduction, a bunch of extension methods are coming soon:

 

 Public static void View <tview> ( This  Ihttphandler Httphandler ){ Httpcontext . Current. response. Redirect (httphandler. url <tview> ());} Public static void View <tview> ( This  Ihttphandler Httphandler,Object Param ){ Httpcontext . Current. response. Redirect (httphandler. url <tview> (PARAM ));} Public static void Viewhome ( This  Ihttphandler Httphandler ){ Httpcontext . Current. response. Redirect ( "~ " );} Public static void Viewlogin ( This  Ihttphandler Httphandler) {viewlogin (httphandler, Null );}Public static void Viewlogin ( This  Ihttphandler Httphandler, String Returnurl ){ String Virtualpath = Formsauthentication . Loginurl; If (! String . Isnullorempty (returnurl) virtualpath + = "? Returnurl =" + Returnurl; Httpcontext . Current. response. Redirect (virtualpath );}

 

End?

Of course it is not over. The above URL only returns a. ASPX page. What about ihttphandler?

 
StringHandlerurl =This. Url <Handler1> ();
 
The above results can also be achieved in the end, but the URL method should be modified as appropriate, so I will not post the code here.

 

Summary:

The last thing to say is that this is an "infinite" idea.

If you want to read other articles that are not so "infinite", there are several other articles below:

Basic data of extension methods

ASP. NET Extension Method

Interesting phenomena brought about by extension methods, interfaces, and inheritance

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.