草庐IT

php - 如何将包含signalR的asp.net mvc页面与其他平台集成

coder 2024-04-20 原文

问题不是 this 的重复问题,虽然提到的问题有一些非常有趣的答案并帮助我更好地理解我的问题,但它不能满足我的需要。让我解释一下我的情况。

我有一个 asp.net mvc 网站,具有通知功能和通过 signalR 和 SQL 依赖项进行实时数据更新。用户身份验证是使用 Identity 2.0 完成的。 仅允许授权用户查看更新的数据/通知。此外,通知/更新因用户而异。我通过实现自定义 UserId 提供程序并使用 Identity 的 UserId 实现了这一点。

现在我想实现以下目标。

  • 简单部分:在其他网站上显示页面(仪表板)的内容,无论其开发语言如何。它可以注入(inject)现有页面或他们(其他网站)想要的任何地方。

  • 困难部分:根据登录用户显示集成部分的实时通知和更新。

在这种情况下执行的最佳操作过程是什么?

更新 由于原始问题因未指定详细信息而被搁置,因此这里是我希望获得建议的详细信息。

我有一个运行在localhost:54603的asp.net mvc网站,下面是home controller的 Action

public ActionResult Index()
{
   HttpContext.Response.AppendHeader("Access-Control-Allow-Origin", "*");
   return View();               
}

索引 View 有一些 signalR 功能。下面是允许 CORS 的 signalR 的启动配置,因为我的目标是向客户端公开索引页面及其全部功能(运行 php 等)

app.Map("/signalr", map =>
{

  map.UseCors(CorsOptions.AllowAll);
  var hubConfiguration = new HubConfiguration
  {
       // You can enable JSONP by uncommenting line below.
       // JSONP requests are insecure but some older browsers (and some
       // versions of IE) require JSONP to work cross domain
       // EnableJSONP = true
   };

  map.RunSignalR(hubConfiguration);
});

我已经创建了 notifcationHub,下面是我在前端的代码(使用代理)。

<script>
    $(function () {
        // Reference the auto-generated proxy for the hub.
        $.connection.notificationHub.url = 'http://localhost:54603/signalr';
        var notification = $.connection.notificationHub;

        // Client side method for receiving the list of notifications on the connected event from the server
        notification.client.refreshNotification = function (data) {
            $("#notificationTab").empty();
            $("#cntNotifications").text(data.length);
            for (var i = 0; i < data.length; i++) {
                $("#notificationTab").append("<tr> <td> " + data[i].Id + "</td> <td>" + data[i].Text + "</td> <td>" + data[i].CreatedDate + "</td></tr>");
            }
        }

        //Client side method which will be invoked from the Global.asax.cs file.
        notification.client.addLatestNotification = function (data) {       
            $("#cntNotifications").text($("#cntNotifications").text() + 1);
            $("#notificationTab").append("<tr> <td> " + data.Id + "</td> <td>" + data.Text + "</td> <td>" + data.CreatedDate + "</td></tr>");
        }

        // Start the connection.
        $.connection.hub.start().done(function () {

            //When the send button is clicked get the text and user name and send it to server.
            $("#btnSend").click(function () {
                notification.server.sendNotification($("#text").val(), $("#userName").val());
            });
            console.log($.connection.hub.id);

        }).fail(function (data) { console.log('Could not connect' + data); });

    });
</script>

Html 紧随其后

@{
    ViewBag.Title = "Home Page";
    Layout = null;
}

<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/signalr/jquery.signalr-2.2.0.min.js"></script>

<script src="@Url.Content("~/signalr/hubs")"></script>

@*<script src="~/signalr/hubs"></script>*@

<div style="width: 70%; padding: 20px">
    <div class="panel panel-primary">
        <div class="panel-heading">

            <! &ndash; To show notification count-->
            <div style="float: left" class="panel-title">Notifications</div>
            <div style="float: right" class="badge" id="cntNotifications"></div>
            <div style="clear: both"></div>


        </div>
        <div class="panel-body">
            <! &ndash; To show All the notifications-->
            <table class="table table-striped table-hover ">
                <thead>
                    <tr>
                        <th>#</th>
                        <th>Text</th>
                        <th>Created Date</th>
                    </tr>
                </thead>

                <tbody id="notificationTab"></tbody>
            </table>
        </div>
    </div>

    <! &ndash; Add panel notification to send notification, Make sure that user enters the user id of the domain they are logged into -->
    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3 class="panel-title">Create Notifications</h3>
        </div>
        <div class="panel-body">
            <div class="form-group">
                <label class="control-label" for="focusedInput">Notification Text</label>
                <input class="form-control" id="text" type="text" value="">
            </div>
            <div class="form-group">
                <label class="control-label" for="focusedInput">Send To</label>
                <input class="form-control" id="userName" type="text" value="">
            </div>
            <a id="btnSend" style="cursor: pointer" class="btn btn-primary">Send Notification</a>
        </div>
    </div>
</div>

该页面按预期正常运行,连接 ID 正在控制台中记录。

现在我创建了另一个 html 页面,下面是它的代码

<html>
<head>
    <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet" />
    <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>  
    <script src="http://ajax.aspnetcdn.com/ajax/signalr/jquery.signalr-2.2.0.min.js"></script> 
</head>
<body>
    <aside>
         <div class="col-lg-2">
              <ul>
                  <li>this</li>
                  <li>is</li>
                  <li>aside</li>
              </ul>
              </div>
    </aside>
    <article>
        <div class="col-lg-10">
            <div id="something">

            </div>
        </div>
    </article>
    <script src="http://localhost:54603/signalr/hubs"></script>
    <script>
        $(document).ready(function () {
            $.ajax({
                url: "http://localhost:54603/Home/Index",
                dataType: 'html',
                crossDomain: true,
                cache:true


            }).done(function (data) {
                $('#something').html(data);
            });
        });
    </script>
</body>
</html>

Ajax 请求返回 html 但 signalR 抛出错误。以下是控制台消息。

GET http://localhost:54603/Home/Index 200 OK 1.18s
Could not connect Error: Error during negotiation request.

我做错了什么导致了这个错误?

最佳答案

很难准确确定您需要做什么,因为这个问题相当广泛,但我希望这些要点对您有所帮助:

SignalR cross-domain在客户端使用 JavaScript,在服务器端使用 CORS,因此您在这方面有所了解。您可以轻松创建一个可以连接到 SignalR channel 的 JavaScript 文件,除了在客户端页面中包含 JavaScript 之外,无需对 PHP 代码进行任何更改。

您可以很容易地在您的服务器上创建一个脚本,客户端可以在他们的页面上引用该脚本,将所需的一切拉到客户端的页面上。因为脚本是从您自己的服务器执行的,所以我认为您不必担心 CORS,因为它不是真正的“跨站点脚本”,因为执行请求的代码将由您的服务器/域“拥有”。

至于身份验证,如果只有您的脚本需要访问身份验证,我认为这意味着您也可以使用您的域的身份验证(cookie 等),不过我必须检查那个。最终,您会使用从包含的脚本向您的域发出 HTTP 请求来验证它们吗?

这里有一些有用的线索,可能有助于解决这个问题:

关于php - 如何将包含signalR的asp.net mvc页面与其他平台集成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33102704/

有关php - 如何将包含signalR的asp.net mvc页面与其他平台集成的更多相关文章

  1. ruby - 如何使用 Nokogiri 的 xpath 和 at_xpath 方法 - 2

    我正在学习如何使用Nokogiri,根据这段代码我遇到了一些问题:require'rubygems'require'mechanize'post_agent=WWW::Mechanize.newpost_page=post_agent.get('http://www.vbulletin.org/forum/showthread.php?t=230708')puts"\nabsolutepathwithtbodygivesnil"putspost_page.parser.xpath('/html/body/div/div/div/div/div/table/tbody/tr/td/div

  2. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  3. python - 如何使用 Ruby 或 Python 创建一系列高音调和低音调的蜂鸣声? - 2

    关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。

  4. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  5. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  6. ruby - 如何将脚本文件的末尾读取为数据文件(Perl 或任何其他语言) - 2

    我正在寻找执行以下操作的正确语法(在Perl、Shell或Ruby中):#variabletoaccessthedatalinesappendedasafileEND_OF_SCRIPT_MARKERrawdatastartshereanditcontinues. 最佳答案 Perl用__DATA__做这个:#!/usr/bin/perlusestrict;usewarnings;while(){print;}__DATA__Texttoprintgoeshere 关于ruby-如何将脚

  7. ruby - 如何指定 Rack 处理程序 - 2

    Rackup通过Rack的默认处理程序成功运行任何Rack应用程序。例如:classRackAppdefcall(environment)['200',{'Content-Type'=>'text/html'},["Helloworld"]]endendrunRackApp.new但是当最后一行更改为使用Rack的内置CGI处理程序时,rackup给出“NoMethodErrorat/undefinedmethod`call'fornil:NilClass”:Rack::Handler::CGI.runRackApp.newRack的其他内置处理程序也提出了同样的反对意见。例如Rack

  8. ruby - 如何每月在 Heroku 运行一次 Scheduler 插件? - 2

    在选择我想要运行操作的频率时,唯一的选项是“每天”、“每小时”和“每10分钟”。谢谢!我想为我的Rails3.1应用程序运行调度程序。 最佳答案 这不是一个优雅的解决方案,但您可以安排它每天运行,并在实际开始工作之前检查日期是否为当月的第一天。 关于ruby-如何每月在Heroku运行一次Scheduler插件?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/8692687/

  9. ruby-on-rails - 如何从 format.xml 中删除 <hash></hash> - 2

    我有一个对象has_many应呈现为xml的子对象。这不是问题。我的问题是我创建了一个Hash包含此数据,就像解析器需要它一样。但是rails自动将整个文件包含在.........我需要摆脱type="array"和我该如何处理?我没有在文档中找到任何内容。 最佳答案 我遇到了同样的问题;这是我的XML:我在用这个:entries.to_xml将散列数据转换为XML,但这会将条目的数据包装到中所以我修改了:entries.to_xml(root:"Contacts")但这仍然将转换后的XML包装在“联系人”中,将我的XML代码修改为

  10. ruby - 检查 "command"的输出应该包含 NilClass 的意外崩溃 - 2

    为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar

随机推荐