简体   繁体   English

从C#控制台应用程序迁移和运行REST API到ASP.NET

[英]Migrating and Running REST API from C# Console Application to ASP.NET

Requirement: 需求:
Need to deploy REST API on Hosting Server. 需要在Hosting Server上部署REST API。 So migrated the code from C# Console Application to ASP.NET which was running successfully on localhost with some errors 因此,将代码从C#控制台应用程序迁移到ASP.NET,该代码在localhost上成功运行,但有一些错误

Here is the below code 这是下面的代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Net;
using System.Diagnostics;

namespace WebAPI
{
    [ServiceContract]
    public interface ICalculator
    {
        [OperationContract, WebInvoke(UriTemplate = "/sum", Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
        double sum(double x, double y);
    }

    public class Calculator : ICalculator
    {
        public double sum(double x, double y)
        {
            return x + y;
        }
    }
    public partial class Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Debug.WriteLine("Initializing URL");
            string baseAddress = "http://localhost:8081/Calculator";
            WebServiceHost myHost = new WebServiceHost(typeof(Calculator), new Uri(baseAddress));

            try
            {
                System.Diagnostics.Debug.WriteLine("Starting Service ...");
                myHost.Open();
            }
            catch (Exception ex)
            {

                //Response.Write(ex);
                //System.Diagnostics.Debug.WriteLine("Exception");
                //myHost.Close();
                //throw new FaultException(ex.Message);
            }
        }

    }
}

Actual Result: 实际结果:

On making/sending the POST Request via PostMan client software, computed values were displayed in addition to that error which was shown on Output window from Debug was 在通过PostMan客户端软件发出/发送POST请求时,除了在Debug的输出窗口中显示的错误之外,还显示了计算值。

The thread 0x3104 has exited with code 0 (0x0).
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Request","time":"2019-03-22T07:52:36.2582149Z","tags":{"ai.internal.sdkVersion":"web: 2.0.0.25000","ai.device.roleInstance":"DESKTOP-5DRIFMH","ai.operation.name":"GET /default.aspx","ai.operation.id":"mHfOluFrMKQ="},"data":{"baseType":"RequestData","baseData":{"ver":2,"id":"mHfOluFrMKQ=","name":"GET /default.aspx","startTime":"2019-03-22T13:22:36.2582149+05:30","duration":"00:00:04.1154559","success":true,"responseCode":"200","url":"http://localhost:29989/default.aspx","httpMethod":"GET","properties":{"DeveloperMode":"true"}}}}
'iisexpress.exe' (CLR v4.0.30319: /LM/W3SVC/2/ROOT-1-131977147547841156): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_32\System.Transactions\v4.0_4.0.0.0__b77a5c561934e089\System.Transactions.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
The thread 0x332c has exited with code 0 (0x0)

After Refreshing the page, an exception was raised by the following codes 刷新页面后,以下代码引发了异常

myHost.Close();

CommunicationObjectFaultedException was unhandled by user code
An exception of type 'System.ServiceModel.CommunicationObjectFaultedException' occurred in System.ServiceModel.dll but was not handled in user code
Additional information: The communication object, System.ServiceModel.Web.WebServiceHost, cannot be used for communication because it is in the Faulted state.


Exception thrown: 'System.InvalidOperationException' in System.ServiceModel.dll
Exception thrown: 'System.ServiceModel.CommunicationObjectFaultedException' in System.ServiceModel.dll
'iisexpress.exe' (CLR v4.0.30319: /LM/W3SVC/2/ROOT-1-131977214492956233): Loaded 'C:\Windows\assembly\GAC_MSIL\Microsoft.VisualStudio.Debugger.Runtime\14.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.Debugger.Runtime.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.

throw new FaultException(ex.Message);

CommunicationObjectFaultedException was unhandled by user code
An exception of type 'System.ServiceModel.CommunicationObjectFaultedException' occurred in System.ServiceModel.dll but was not handled in user code
Additional information: The communication object, System.ServiceModel.Web.WebServiceHost, cannot be used for communication because it is in the Faulted state.


Exception thrown: 'System.InvalidOperationException' in System.ServiceModel.dll
Exception
Exception thrown: 'System.ServiceModel.CommunicationObjectFaultedException' in System.ServiceModel.dll
'iisexpress.exe' (CLR v4.0.30319: /LM/W3SVC/2/ROOT-1-131977154884215275): Loaded 'C:\Windows\assembly\GAC_MSIL\Microsoft.VisualStudio.Debugger.Runtime\14.0.0.0__b03f5f7f11d50a3a\Microsoft.VisualStudio.Debugger.Runtime.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.

Without the Catch Block, the below exception was getting stacked in the Diagnostic Tools window from the Events tab 如果没有Catch Block,则会在“事件”选项卡的“诊断工具”窗口中堆叠以下异常

Exception: Exception thrown: 'System.InvalidOperationException' in System.ServiceModel.dll ("The ChannelDispatcher at 'http://localhost:8081/Calculator' with contract(s) '"ICalculator"' is unable to open its IChannelListener."). Exception thrown: 'System.InvalidOperationException' in System.ServiceModel.dll ("The ChannelDispatcher at 'http://localhost:8081/Calculator' with contract(s) '"ICalculator"' is unable to open its IChannelListener.")

How would I need to catch these exceptions 我怎么需要捕获这些异常

Changing the string baseAddress = "http://somedomain.xy:8081/Calculator"; 更改string baseAddress = "http://somedomain.xy:8081/Calculator"; and uploading it to the server in the PostMan it was displaying as 并将其上传到显示为的PostMan中的服务器

Could not get any response There was an error connecting to http://somedomain.xy:8081/Calculator/sum . 无法得到任何回复连接到http://somedomain.xy时出错:8081 /计算器/总和

Expected Result: 预期结果:
Making calls via PostMan the computed values should need to be displayed 通过PostMan进行调用时,需要显示计算值
Since I needed to make the service up and running on hosting server. 因为我需要在托管服务器上启动并运行服务。 As I'm neither able to figure out the root cause nor the solutions for the whole problem, whether it is popping out from the coding part or the problem with the port? 因为我既无法找出问题的根本原因,也无法解决整个问题的解决方案,无论是从编码部分弹出还是端口问题?

The thread 0x3104 has exited with code 0 (0x0).
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Request","time":"2019-03-22T07:52:36.2582149Z","tags":{"ai.internal.sdkVersion":"web: 2.0.0.25000","ai.device.roleInstance":"DESKTOP-5DRIFMH","ai.operation.name":"GET /default.aspx","ai.operation.id":"mHfOluFrMKQ="},"data":{"baseType":"RequestData","baseData":{"ver":2,"id":"mHfOluFrMKQ=","name":"GET /default.aspx","startTime":"2019-03-22T13:22:36.2582149+05:30","duration":"00:00:04.1154559","success":true,"responseCode":"200","url":"http://localhost:29989/default.aspx","httpMethod":"GET","properties":{"DeveloperMode":"true"}}}}
'iisexpress.exe' (CLR v4.0.30319: /LM/W3SVC/2/ROOT-1-131977147547841156): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_32\System.Transactions\v4.0_4.0.0.0__b77a5c561934e089\System.Transactions.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
The thread 0x332c has exited with code 0 (0x0)

These lines in the Output window are all totally normal and can be ignored (threads exiting with non-error code 0 when they are no longer in use, telemetry logging, assemblies being loaded into the IIS process). “输出”窗口中的这些行都是完全正常的,可以忽略(当不再使用时,线程退出时出现非错误代码0,遥测日志记录,程序集被加载到IIS进程中)。

The specific error your're getting afterwards is because you're trying to host the WCF service multiple times. 您之后遇到的具体错误是因为您尝试多次托管WCF服务。 This is why it works the first time you load the page, but fails after refreshing the page (because you've reconfigured and re-started another instance of the service). 这就是它第一次加载页面时的工作原理,但在刷新页面后失败(因为您已重新配置并重新启动了另一个服务实例)。

While your code would work in a Console application, this is not how you host a WCF service in IIS. 虽然您的代码可以在控制台应用程序中运行,但这不是您在IIS中托管WCF服务的方式。 There's a detailed walkthrough of that setup here on the Microsoft Docs site: 在Microsoft Docs站点上有一个详细的设置演练:

Deploying an Internet Information Services-Hosted WCF Service 部署Internet信息服务托管WCF服务

While the full tutorial is not really appropriate for a Stack Overflow answer, I will quote the general steps: 虽然完整的教程不适合Stack Overflow答案,但我将引用一般步骤:

  • Ensure that IIS, ASP.NET, WCF, and the WCF activation component are correctly installed and registered. 确保正确安装和注册了IIS,ASP.NET,WCF和WCF激活组件。

  • Create a new IIS application, or reuse an existing ASP.NET application. 创建新的IIS应用程序,或重用现有的ASP.NET应用程序。

  • Create a .svc file for the WCF service. 为WCF服务创建.svc文件。

  • Deploy the service implementation to the IIS application. 将服务实现部署到IIS应用程序。

  • Configure the WCF service. 配置WCF服务。

As said by Crowcoder & Josh Darnell, we need to create WCF service by then and can be hosted on any domain without causing problems around the port 正如Crowcoder和Josh Darnell所说,我们需要在那时创建WCF服务,并且可以托管在任何域上而不会导致端口出现问题

Here in my Git repo, you can find entire Calculator code attached with publishing on to the server also. 在我的Git仓库中,您可以找到附带的所有计算机代码,也可以发布到服务器上。 GitHub Repo GitHub回购

You can disable the telemetry service in the command prompt by 您可以在命令提示符下禁用遥测服务

set DOTNET_CLI_TELEMETRY_OPTOUT=1 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM