How can i Add SignalR to my WCF Service and MVC 4

2019-06-07 03:42发布

问题:

I am Developing a project for ASp.net MVC 4 client Application with WCF Service. I created a controller inside the MVC and added a view in it. and Also,i passed the data from view with ajax and jquery..after response from service,the result data value is stored in a html element.like that i am implemented.One part is completed.And the Second Part is

I have an idea to add functionality ok SignalR in WCF and MVC4 Service?

I thought SignalR is an Self-Hosted?

How do i create a api for signalR in WCF and MVC4..below is my code are.

MVC Controller:-

       using System;
       using System.Collections.Generic;
       using System.Linq;
       using System.Web;
       using System.Web.Mvc;

       namespace MVC4.Controllers
        {
          public class SampleController : Controller
           {
               public ActionResult Index()
            {

                 return View();
            }

      }
   }

View:-

  @{
     Layout = null;
   }

   <!DOCTYPE html>

   <html>
   <head>
   <meta name="viewport" content="width=device-width" />
   <title>Index</title>
   <script src="~/Scripts/jquery-1.8.2.js"></script>
   <script src="~/Scripts/jquery-1.8.2.min.js"></script>
   <script type="text/javascript">
   $(document).ready(function () {
      var u = $(".user");
      var l = $("li");
      $(u).focusout(function () {
      var User = u.val();
      $.ajax({
                type: "GET",
                contentType: "application/json;charset=utf-8",
                url: "http://localhost:64712/Service1.svc/GetValue",
                data: { "username": User },
                success: function (data) {
                    var c = data['GetValueResult'];
                    console.log(c);

                        console.log(c);

                        l.append(c);

                },
            });
        });
    });

   </script>
   <style>
   div.show
   {
        height:250px;
        width:500px;
        background-color:indianred;
        box-sizing:border-box;
    }
    ul.data
    {
        height:250px;
        width:500px;
        background-color:beige;
        box-sizing:border-box;
    }
</style>
</head>
<body>
<div class="show">
       <p>UserID</p>
       <input type="text"  class="user"/>
</div>
<ul class="data">
    <li></li>
</ul></body> 
</html>

Here is the Router Configuration...this is the final changes,i MVC part is completed.

RouteConfig.cs:-

  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Web;
  using System.Web.Mvc;
  using System.Web.Routing;
  namespace MVC4
    {
       public class RouteConfig
        {
           public static void RegisterRoutes(RouteCollection routes)
            {
                routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
                routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Sample", action = "Index", id =  UrlParameter.Optional }
                );
           }
         }
     }

WCF Service:-
this is Service1.svc.cs:-

    public class Service1 : IService1
       {
            public string GetValue(string username)
            {
                 string u = "username="+username;

                 Console.WriteLine("u=" + u);

                  return u;
            }

        }

and the IService.cs file is :-

     public interface IService1
      {

          [OperationContract]
          [WebInvoke(Method="GET")]
          string GetValue(string username);

      }

And this is my Global Application Class:-

    public class Global : System.Web.HttpApplication
    {

    protected void Application_Start(object sender, EventArgs e)
    {

    }

    protected void Session_Start(object sender, EventArgs e)
    {

    }

    protected void Application_BeginRequest(object sender, EventArgs e)
    {
        if (HttpContext.Current != null)
        {
            HttpContext.Current.Response.Headers.Add("Access-Control-Allow-Origin", "*");

            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.Headers.Add("Access-Control-Allow-Methods", " POST,GET");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.End();
            }
        }

    }

    protected void Application_AuthenticateRequest(object sender, EventArgs e)
    {

    }

    protected void Application_Error(object sender, EventArgs e)
    {

    }

    protected void Session_End(object sender, EventArgs e)
    {

    }

    protected void Application_End(object sender, EventArgs e)
    {

    }
}

And this is the Web.Config File:-

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
   <appSettings>
      <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
   </appSettings>
   <system.web>
      <compilation debug="true" targetFramework="4.5" />
      <httpRuntime targetFramework="4.5" />
   </system.web>
   <system.serviceModel>
      <services>
         <service name="WCF_2.Service1">
            <endpoint address="" contract="WCF_2.IService1" binding="webHttpBinding" bindingConfiguration="" behaviorConfiguration="web" />
         </service>
      </services>
      <behaviors>
         <serviceBehaviors>
            <behavior>
               <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
               <serviceDebug includeExceptionDetailInFaults="false" />
            </behavior>
         </serviceBehaviors>
         <endpointBehaviors>
            <behavior name="web">
               <webHttp helpEnabled="false" defaultBodyStyle="Wrapped" defaultOutgoingResponseFormat="Json" />
            </behavior>
         </endpointBehaviors>
      </behaviors>
      <protocolMapping>
         <add binding="basicHttpsBinding" scheme="https" />
      </protocolMapping>
      <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
   </system.serviceModel>
   <system.webServer>
      <modules runAllManagedModulesForAllRequests="true" />
      <directoryBrowse enabled="true" />
   </system.webServer>
</configuration>

Could Anyone provide me an solution for SignalR interface .

Is it possible to add SignalR to WCF Service and MVC4..how do i configure them succesfully?