如何在 C# 中的 WebMethod 中定义 if 语句

How to define an if statement in WebMethod in C#

我试图在我的网站页面上的一个 WebMethods 中定义一个 if 语句,以检查 University Offer 字段的值是否为 null,如果该值为 null,则该方法按预期执行。如果该值不为空,那么我希望它 return 一条错误消息。

麻烦的是我似乎遇到了两个问题。

  1. 我在 else 条件中输入什么来指示将此值保存到此字段时出错?我尝试了 return,但我的方法有一个 return 类型的 void,这使得 return 过程难以实现。

  2. 当我执行我的代码并在我的服务器上对其进行测试时,尝试访问该特定方法会返回一条消息,指示 “测试表单仅可用于来自本地计算机的请求。

这是我到目前为止能够定义的方法的代码。

[WebMethod]
public void EditNAA_ApplicationOffer(NAA_Applications App, int ApplicationId, string UniversityOffer)
{

    NAA_Applications _EditAO = _NAAService.Get_Applicant_Application(ApplicationId);

    if (_EditAO.UniversityOffer == null)
    {
        _NAAService.EditNAA_ApplicationOffer(ApplicationId, UniversityOffer);
    }
    else
    {

    }


}

谁能帮我解决这两个问题?

  1. What do I put in the else condition to indicate there was an error in saving this value to this field?

您可以通过抛出 SoapException:

来指示 Web 方法中发生了错误
if (_EditAO.UniversityOffer == null)
{
    _NAAService.EditNAA_ApplicationOffer(ApplicationId, UniversityOffer);
}
else
{
    throw new SoapException("Some error has occurred", SoapException.ClientFaultCode);
}

在这种情况下,您将在客户端收到 HTTP 错误 500 以及提供的错误消息。

  1. When I execute my code and test it on my server, trying to access that specific method comes back with a message indicating "The test form is only available for requests from the local machine.

默认设置不允许通过远程主机的测试表单调用服务。如果您同意允许任何人使用您的服务,您应该将以下 <webServices> 部分添加到您的 web.config(取自 this answer):

<configuration>
    <system.web>
     <webServices>
        <protocols>
            <add name="HttpGet"/>
            <add name="HttpPost"/>
        </protocols>
    </webServices>
    </system.web>
</configuration>