ASP. net mvc 3.0: Ajax-based form submission. After Authentication fails on page A, the page is forced to go to the logon page. How can I return to page a after successful logon?

Source: Internet
Author: User
Tags custom name

Address: http://www.cnblogs.com/luoxiaonet/archive/2011/12/13/2285326.html#commentform

 

The homepage of many websites provides information input, regardless of whether you have an account and have logged on. For example, I like 42qu (I have nothing to do with the Founder. I only like this website and have no intention of advertising. If you are interested, you can check it out ). When I post my own "broken thoughts", I will be automatically redirected to the logon page, and the problem is whether I can return to the original page after the logon is successful. It seems that this problem is a little poor, but its implementation framework is MVC 3.0, and it has been trying for many days to find its elegant implementation method. I would like to share it with you.

Let's take a final look:

The page is divided into two areas. One is the broken post area (the previous part) and the other is the presentation area (the lower part) to extract data from the real page. Information submission is based on Ajax. beginform (), and then the rendering area is no longer refreshed.

Let's see how the Form Based on Asynchronous submission is stated:

Important attributes include:UpdatetargetidIt indicates the DIV to which the asynchronously loaded data will be presented. In addition, the onsuccess event is particularly important, and it plays an important role in callback processing. Finally, to load the data in the asynchronous request to the specified Div, you must reference the jquery. Validate. unobtrusive. Min. js script file (line 1 ):

The functions of this JS file are similar to the updatepanel control in ASP. NET Ajax.

Now I want to post a broken message and try to click "Broken message" to send the message. Because I have not logged on to the website for nearly a week, the related Cookie has expired and the page will be forced to go to the login page (login. cshtml), jump itself is my design intent, but the page shows bad results, because the entire login page is displayed in the DIV with the ID "chatintegrationcontent, the page can be imagined as absurd, so I have to solve two problems:

1. Default Authentication attributesAuthorizeattributeI have to customize the authentication class.LoginauthorizeattributeAnd inherit from it, and override (override) the protected virtual method (protected virtual method );

2. Any jump to the server is obviously futile: no matter whether it is redirect or the redirection simulation server. Transfer Mode to jump to the curve, it will fall into the DIV specified by the original updatetargetid attribute. At first, I thought, can I cancel Ajax calling on the server? It is converted into a normal call, that is, the POST request of a common form such as @ html. beginform. The answer is no! This request is generated asynchronously by Ajax, and its fate is doomed. Therefore, the only way is to notify the client script for window. Location jump!

The cause is Ajax asynchronous calls. To solve this problem, you must start with it and see how the custom authentication class is:

InheritanceAuthorizeattributeThen, only the virtual function protected virtual void handleunauthorizedrequest (authorizationcontext filtercontext) is rewritten. This means the form is as follows: [authorize (roles = "member")] the authentication logic is still based on MVC 3.0.AlgorithmAfter reading its source code, it is indeed much more elegant and comprehensive than I have set up another stove. I am ashamed to implement a hundred lines of work.CodeAll objects are deleted, so the reusability of the object orientation is really great. As you can see, the attribute result of the context object filtercontext has been setJsonresult. Note that the failure of authorize attribute authentication causes the MVC Framework to jump to the logon page (specified by the loginurl attribute) because a 401 exception is thrown ):

The loginurl attribute explicitly specifies the logon page. According to the Dudu boss's suggestion, cookieless is also explicitly specified as usecookies to facilitate the test of cookies and authentication tickets (Ticket) set only one minute (timeout = "1 ").

The most important sentence of the above Code is: filtercontext. httpcontext. Request.Isajaxrequest()

It torture whether the current request is an asynchronous Ajax request. The reason for this judgment is that the client sends the request based on @ HTML. for normal beginform () requests, the server can easily jump to and refresh the entire browser without worrying that the login page falls into the related Div. On the contrary, Ajax requests require more care, it must notify the JS script for client jump (window. location) to ensure that the logon page isRefresh the entire browser. Encapsulate a key-Value Pair in JSON format and return it to the client:

The "JSON format content" class jsonresult inherited from actionresult has an object-type attribute data dedicated for loading data. Currently, only one key-value pair is required. In addition, jsonrequestbehavior = jsonrequestbehavior. allowget also plays an important role: to avoid JSON hijacking attacks, any request returned in the jsonresult class from mvc2.0 does not allow get Ajax requests to obtain data, even if only one key-value pair is in the data object, the compromised adoption of post requests will also make the data unable to be cached by the browser. In fact, the sensitivity of the data is not high, so the adoptionGET requestIs a good development experience! So far, the server has responded to the Ajax request sent from the client when the authentication fails, notifying the client script "I failed to verify you" ---- ajax_unauthorized.

Remember the onsuccess attribute in Ajax. beginform? Now let's look at its JS functions:

The client simply receives the notification. If the notification information is consistent, the window. Location is directly assigned as a page Jump to refresh the entire browser. Request. url is used to obtain the route URL of the current page and carry it together as a jump path parameter. The result is shown as follows:

Http: // localhost: 1650/account/logon?Returnurl= Http % 3A % 2f % 2 flocalhost % 3a1650% 2f

When you go to the logon page, you must first enter the form. After the form is submitted and the logon verification is successful, you can use the returnurl parameter value to jump back to the original page, so we need to save the returnurl parameter value for a moment to see the logon. cshtml login table header:

The third parameter of beginform () is the route parameter: Object routevalues. We save the "Return page" here. This parameter will be submitted to the server when the login form is submitted in the future, handled by the action marked with the httppost feature:

The returnurl parameter in the route URL can be obtained using the action specified in httppost as the parameter: Obviously, the first is the login form entity, and the second is its parameter.

You only need to determine whether the input parameter returnurl is null, so you can make an appropriate jump selection. As long as the returnurl is a specific URL, you can return a smooth response, this is a simple and elegant solution for mvc3.0 to return to the original page.

Category: ASP. NET Green Channel
Follow-39
Fans-1 + Add follow20(PleaseArticle(Comments) «previous article by the blogger: ASP. net mvc 3.0: How the razor view engine displays multiple entities

Posted @ I don't know how to read (1020) Comments (8) edit my favorites

Post comments2269913View reply reference

# 1st FloorChairo42qu is not made by python? How does it become. Net mvc3.0?View reply reference

#2 floor [Landlord]2011-12-14 07:23Don't feel like water

Reference

Chairo: 42qu is not made by python? How does it become. Net mvc3.0?

Well, it's Python.
Mvc3 is my own method. View Delete changes

# Third FloorBlack fanReturnurl = request. URL. If the login is invalid during post, the request is retrieved at this time. the URL address is the post path address. It is obviously incorrect to jump to this address after logon. How can this problem be solved?View reply reference

# 4th floorC # general permission management system componentsThe code looks very standard and the layout is good.
Continue to write your blog.View reply reference

# 5th floorV. EnjoyVery good! Hard work! Thank you for sharing!View reply reference

# 6th floor [Landlord]Don't feel like water

Reference

Black fan: returnurl = request. URL. If the login is invalid during post, the request is retrieved at this time. the URL address is the post path address. It is obviously incorrect to jump to this address after logon. How can this problem be solved?

Reference

Black fan: returnurl = request. URL. If the login is invalid during post, the request is retrieved at this time. the URL address is the post path address. It is obviously incorrect to jump to this address after logon. How can this problem be solved?

Thank you for your question.
For example, if there is a function page A, its route URL is: http: // localhost: 1066/
Enter some text in the text box. It is expected that the text information will be asynchronously submitted to the action processing (called createchat) at the Controller layer ), but in fact, there is an interception filter before the action is executed (the custom name is loginauthorize). When it finds that you have not logged on or have no corresponding permission, it will return a JSON object for your asynchronous request, and quickly hand over the control to the client (this explicitly shields the server from throwing 401 exceptions), which means "Your authentication failed, please check it out ", after the client script obtains control, it will not be indifferent. It immediately checks the JSON key value in the callback function. If it is "ajax_unauthorized", it will realize "oh, I am wrong, I should log on. the URL gets its own route URL (http: // localhost: 1066/. the location browser redirects to the logon page, so the "Jump to this address is obviously incorrect" will not happen.
Next, on the logon page, if the logon verification fails (the account does not exist or the password is incorrect), you will stay on the logon page. If the verification succeeds, that is, when the returnurl parameter of logon is not empty, "Return redirect (returnurl)" will go to page.
You can create an MVC project. View Delete changes

# 7th floorBlack fan

Reference

Don't feel like water:

Reference

Black fan: returnurl = request. URL. If the login is invalid during post, the request is retrieved at this time. the URL address is the post path address. It is obviously incorrect to jump to this address after logon. How can this problem be solved?

Reference

Black fan: returnurl = request. URL. If the login is invalid during post, the request is retrieved at this time. the URL address is the post path address. It is obviously incorrect to jump to this address after logon. How can this problem be solved?

Thank you for your question.
For example, if there is a function page A, its route URL is: http: // localhost: 1066/
In...

Thank you for your answer. But if it is not an Ajax submission, Where can the returnurl be obtained? What is the loginauthorize (apparently incorrect) blocker )? It would be complicated to obtain the post before submission. There is a good way to reply to the reference.

# Floor 8 [Landlord]Don't feel like water

Reference

Black fan:

If it is not an Ajax request and you want to return to this page later, it means that when posting text information, you have to submit the route URL of page A as a parameter to the expected action (called createchat). When the custom filter loginauthorize intercepts the URL, you are not logged on, the processing method is divided into two situations:
1. This is the processing of this article. Ask if the client request is an Ajax request. If the custom filter loginauthorize has the isajaxreuquest () Judgment, immediately hand over the control to the client;
2. If it is not an Ajax request, that is, the form on the client is in the form of @ html. beginform (), you only need to add one transmission parameter to the single table header: request. url. The complete syntax is like this:
@ Using (html. beginform ("createchat", "chat", new {returnurl = request. url}, formmethod. Post ))
{
// Prompt: the code is not tested
}
It can be found that the request. url is automatically sent to the server when it is submitted for the first time, instead of waiting for a notification from the server as the Ajax request to force jump to window. Location and then carry it with parameters.
This is your desire to "get and post before submission" (that is, after you change it to an HTML form, add another route parameter ).

Request. the URL is uploaded to the server. When we try to use authorize [] as the login verification method without any processing by default, once the verification fails, the MVC Framework will throw a 401 exception, and then according to the Web. the configuration information (in the body) in config is redirected to the logon page without any parameters, and how to pass the returnurl! Therefore, when the custom filter loginauthorize is running and the MVC framework fails to authenticate and determines that it is not an Ajax request, you can explicitly redirect it to the logon page and carry the URL to it:
Return redirecttoaction ("Logon", "Account", new {returnurl = request. querystring ["returnurl"]. tostring });
The logon code on the logon page is the same as that on the original page. You do not need to change it, that is, logon does not care whether you are Ajax or not.

The homepage of many websites provides information input, regardless of whether you have an account and have logged on. For example, I like 42qu (I have nothing to do with the Founder. I only like this website and have no intention of advertising. If you are interested, you can check it out ). When I post my own "broken thoughts", I will be automatically redirected to the logon page, and the problem is whether I can return to the original page after the logon is successful. It seems that this problem is a little poor, but its implementation framework is MVC 3.0, and it has been trying for many days to find its elegant implementation method. I would like to share it with you.

Let's take a final look:

The page is divided into two areas. One is the broken post area (the previous part) and the other is the presentation area (the lower part) to extract data from the real page. Information submission is based on Ajax. beginform (), and then the rendering area is no longer refreshed.

Let's see how the Form Based on Asynchronous submission is stated:

Important attributes include:UpdatetargetidIt indicates the DIV to which the asynchronously loaded data will be presented. In addition, the onsuccess event is particularly important, and it plays an important role in callback processing. Finally, to load the data in the asynchronous request to the specified Div, you must reference the jquery. Validate. unobtrusive. Min. js script file (line 1 ):

The functions of this JS file are similar to the updatepanel control in ASP. NET Ajax.

Now I want to post a broken message and try to click "Broken message" to send the message. Because I have not logged on to the website for nearly a week, the related Cookie has expired and the page will be forced to go to the login page (login. cshtml), jump itself is my design intent, but the page shows bad results, because the entire login page is displayed in the DIV with the ID "chatintegrationcontent, the page can be imagined as absurd, so I have to solve two problems:

1. Default Authentication attributesAuthorizeattributeI have to customize the authentication class.LoginauthorizeattributeAnd inherit from it, and override (override) the protected virtual method (protected virtual method );

2. Any jump to the server is obviously futile: no matter whether it is redirect or the redirection simulation server. Transfer Mode to jump to the curve, it will fall into the DIV specified by the original updatetargetid attribute. At first, I thought, can I cancel Ajax calling on the server? It is converted into a normal call, that is, the POST request of a common form such as @ html. beginform. The answer is no! This request is generated asynchronously by Ajax, and its fate is doomed. Therefore, the only way is to notify the client script for window. Location jump!

The cause is Ajax asynchronous calls. To solve this problem, you must start with it and see how the custom authentication class is:

InheritanceAuthorizeattributeThen, only the virtual function protected virtual void handleunauthorizedrequest (authorizationcontext filtercontext) is rewritten. This means the form is as follows: [authorize (roles = "member")] this authentication logic still uses the MVC 3.0 algorithm. After reading its source code, it is indeed much more elegant than I wrote in another stove, I am ashamed to delete all the hundreds of lines of code I have implemented. the reusability of object-oriented code is really great. As you can see, the attribute result of the context object filtercontext has been setJsonresult. Note that the failure of authorize attribute authentication causes the MVC Framework to jump to the logon page (specified by the loginurl attribute) because a 401 exception is thrown ):

The loginurl attribute explicitly specifies the logon page. According to the Dudu boss's suggestion, cookieless is also explicitly specified as usecookies to facilitate the test of cookies and authentication tickets (Ticket) set only one minute (timeout = "1 ").

The most important sentence of the above Code is: filtercontext. httpcontext. Request.Isajaxrequest()

It torture whether the current request is an asynchronous Ajax request. The reason for this judgment is that the client sends the request based on @ HTML. for normal beginform () requests, the server can easily jump to and refresh the entire browser without worrying that the login page falls into the related Div. On the contrary, Ajax requests require more care, it must notify the JS script for client jump (window. location) to ensure that the logon page isRefresh the entire browser. Encapsulate a key-Value Pair in JSON format and return it to the client:

The "JSON format content" class jsonresult inherited from actionresult has an object-type attribute data dedicated for loading data. Currently, only one key-value pair is required. In addition, jsonrequestbehavior = jsonrequestbehavior. allowget also plays an important role: to avoid JSON hijacking attacks, any request returned in the jsonresult class from mvc2.0 does not allow get Ajax requests to obtain data, even if only one key-value pair is in the data object, the compromised adoption of post requests will also make the data unable to be cached by the browser. In fact, the sensitivity of the data is not high, so the adoptionGET requestIs a good development experience! So far, the server has responded to the Ajax request sent from the client when the authentication fails, notifying the client script "I failed to verify you" ---- ajax_unauthorized.

Remember the onsuccess attribute in Ajax. beginform? Now let's look at its JS functions:

The client simply receives the notification. If the notification information is consistent, the window. Location is directly assigned as a page Jump to refresh the entire browser. Request. url is used to obtain the route URL of the current page and carry it together as a jump path parameter. The result is shown as follows:

Http: // localhost: 1650/account/logon?Returnurl= Http % 3A % 2f % 2 flocalhost % 3a1650% 2f

When you go to the logon page, you must first enter the form. After the form is submitted and the logon verification is successful, you can use the returnurl parameter value to jump back to the original page, so we need to save the returnurl parameter value for a moment to see the logon. cshtml login table header:

The third parameter of beginform () is the route parameter: Object routevalues. We save the "Return page" here. This parameter will be submitted to the server when the login form is submitted in the future, handled by the action marked with the httppost feature:

The returnurl parameter in the route URL can be obtained using the action specified in httppost as the parameter: Obviously, the first is the login form entity, and the second is its parameter.

You only need to determine whether the input parameter returnurl is null, so you can make an appropriate jump selection. As long as the returnurl is a specific URL, you can return a smooth response, this is a simple and elegant solution for mvc3.0 to return to the original page.

Related Article

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.