Step-by-step learning signalr for real-time communication _3_ cross-domain resolution via cors

Source: Internet
Author: User

The original: Step-by-step learning signalr for real-time communication _3_ cross-domain resolution via cors

Step-by-step learning signalr for real-time communication \_3_ cross-domain resolution via cors

SignalR

    • Step-by-step learning signalr for real-time communication _3_ cross-domain resolution via cors
      • Objective
      • A supplement to start ()
      • Cross-Domain Solutions
        • JSONP
        • CORS
          • Cors Cross-Domain Demo
      • Conclusion
      • Reference documents

Objective

This week the work is relatively busy, has not had the time to study signalr, the general hope can write an article about SIGNALR in a week. The previous article with persistent connections way to achieve a simple online chat function, this time we continue to learn deeply.

A supplement to start ()

In the previous article, the foreground HTML page we created a few JavaScript, the code below, you can also download the last source.

  
 
  1. <!DOCTYPE html>
  2. xmlns="http://www.w3.org/1999/xhtml">
  3. <title>persistent connections</title>
  4. <script src="Scripts/jquery-1.10.2.min.js"></script>
  5. <script src="Scripts/jquery.signalR-2.0.0.min.js"></script>
  6. <body>
  7. Echo service
  8. <div>
  9. <input type="text" id="text" />
  10. <button id="send">Send</button>
  11. </div>
  12. <script>
  13. $(function () {
  14. var connection = $.connection("/echo");
  15. connection.logging = true;
  16. connection.received(function (data) {
  17. $("body").append(data + "<br />");
  18. });
  19. connection.error(function (err) {
  20. alert("存在一个错误. \n" +
  21. "Error: " + err.message);
  22. });
  23. connection.start().done(function () {
  24. $("#send").click(function () {
  25. connection.send($("#text").val());
  26. $("#text").val("").focus();
  27. });
  28. });
  29. });
  30. </script>
  31. </body>

Here's how to do it: by code var connection = $.connection("/echo");
We create a connection by opening the connection.start().done() connection and handling the events we need to handle when the connection is complete.
If you put the following code

 
   
  
  1. connection.start().done(function () {
  2. connection.send(‘Hi‘);
  3. });

Divided into 2 sections, such as:

 
   
  
  1. connection.start();
  2. connection.send(‘Hi‘);

then you must pay attention to:
Although you have connection.send() previously invoked the connection.start() connection, but connection.start() it is an async method, it means that it is possible that when you call the connection.send() connection is not open, then the project will error.
The correct method, as shown in the previous code, is followed by a code that fails to open:

  
 
  1. var connection = $.connection("/echo");
  2. connection.start(function() {
  3. // 连接开启成功才会进入这里
  4. connection.send("Hi");
  5. }).fail(function() {
  6. //连接开启失败则进入这里
  7. alert("服务开启失败");
  8. });
Cross-Domain Solutions

In the previous article, students asked about cross-domain issues, then in the next time I will take everyone to study together.
There are two ways to solve cross-domain SIGNALR: The first is JSONP, and the second is cors.

JSONP

If your service has to support the old version of the browser, then JSONP is the only choice, otherwise in security considerations This is not recommended, specifically what security factors I do not know (some of the students can explain), based on the case of fast learning, we do not need to dwell on this. The server disables this feature by default, and we can activate this feature by providing an Connectionconfiguration object and setting the Enablejsonp property to True by initializing.

  
 
  1. public class Startup
  2. {
  3. public void Configuration(IAppBuilder app)
  4. {
  5. var config = new ConnectionConfiguration()
  6. {
  7. EnableJSONP = true
  8. };
  9. app.MapSignalR<EchoConnection>("/echo", config);
  10. }
  11. }

I think the code should be well understood, as we mentioned earlier MapSignalR<TConnection>() there are many overloaded methods, and this is another overloaded method that is configured by providing an ConnectionConfiguration object.

CORS

Cors is a standalone framework that can easily solve cross-domain issues through NuGet installation
installation command: Install-Package microsoft.owin.cors
Cors is implemented through Owin, so we need to do some configuration on the project when it starts, and do the SIGNALR mapping as if it were configured in startup.

  
 
  1. public class Startup
  2. {
  3. public void Configuration(IAppBuilder app)
  4. {
  5. //app.MapSignalR<EchoConnection>("/echo");
  6. app.Map("/echo",
  7. map => {
  8. map.UseCors(CorsOptions.AllowAll);
  9. map.RunSignalR<EchoConnection>();
  10. }
  11. );
  12. }
  13. }

The code should not be difficult, this time we app.Map() map, the first parameter is the address of the map, the second parameter is a lambda expression, by UseCors(CorsOptions.AllowAll) allowing cross-domain.

Cors Cross-Domain Demo

Jsonp I'm not doing a demo. Interested can try it on their own, and next I'll do a cross-domain chat through cors. First, I'll make a copy of the last project, save it from re-hitting the code and change the name of the copied project from signalr_1 to signalr_2_cors.
The project directory looks like this:

Save trouble, I deployed signalr_1 on IIS, which served as a remote SIGNALR service.

After successful deployment,:

At this point we talk about the Signalr_2_cors project slightly modified
1. Delete the mapping in startup, at this time Signalr_2_cors has not done SIGNALR server, only to do the client to connect the services provided by signalr_1

2. Change echo to var connection = $.connection("/echo");
var connection = $.connection("http://127.0.0.1:8083/echo");

Then run the Echo page in Signalr_2_cors, and the result:

There was an error that we wrote ourselves.

Because our signalr_1 does not allow cross-domain connections, of course we cannot connect in signalr_2_cors , and then we allow cross-domain connectivity in project one.

Re-compile the project and then refresh the next signalr_1 echo.html page, note our page address

Then refresh the next signalr_2_cors page and note the address

Connection success, no error, send a message try (ˇ?ˇ)

Conclusion

The cross-domain problem of signalr is realized through cors, so it's easy to try it out in a cross-domain.

Note: When installing the Cors package through NuGet, I am prompted unable to find the "Microsoft.AspNet.Cors" I have FQ, so this should not need FQ to download, But in the NuGet page search does have this package, specifically what causes I am not clear, if you have encountered this problem please download unzip and add reference can, because rely on Microsoft.AspNet.Cors Microsoft.AspNet.Cors , so the inside of 2 package to add a reference

SOURCE download
This article publishes to the job tribe

Reference documents

SignalR programming in Microsoft asp PDF download

Step-by-step learning signalr for real-time communication _3_ cross-domain resolution via cors

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.