Web Services 无法在.NET 4.0中使用SoapHeader验证Web服务

vyu0f0g1  于 2022-11-15  发布在  .NET
关注(0)|答案(1)|浏览(134)

我的Web服务有以下控制器类。我尝试使用SoapHeader向其添加身份验证。系统使用的是.NET 4.0。我的代码如下所示:

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
using System.IO;
using System.Web.Services.Protocols;

public class AuthHeader : System.Web.Services.Protocols.SoapHeader
{
    public string username { get; set; }
    public string password { get; set; }

    public bool IsValid()
    { 
        return this.username == "admin" && this.password == "admin";
    }

}

[WebService(Namespace = "http://tempuri.org")]
[WebServiceBinding(ConformsTo = WsiProfiles.None)]
[ScriptService]
public class FormController: System.Web.Services.WebService
{
    public AuthHeader auth;

    
    [WebMethod]
    [SoapHeader ("auth")]
    public string GetFormTypes()
    {
        if (auth != null)
        {
            if (auth.IsValid()) {
                var obj = SQLQueries.ParseQuery(false, "select * from form");
                Debug.WriteLine(obj);
                obj.WriteToResponse();
                return "Successfully authenticated";
            }
                
            else {
                var res = "Invalid credentials";
                return res;
            }
                
        }
        else
        {
            var res = "Error in authentication";
            return res;
        }
    }
}

我正在使用 Postman 工具测试它。我的有效载荷主体看起来像:

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Header>
    <AuthHeader xmlns="http://tempuri.org">
      <username>admin</username>
      <password>admin</password>
    </AuthHeader>
  </soap:Header>
  <soap:Body>
    <GetFormTypes xmlns="http://tempuri.org" />
  </soap:Body>
</soap:Envelope>

我在网上查过的所有例子,包括微软的官方文档,都是以类似的方式做的,但是我的代码不起作用。当我发送请求时,soap头的值auth总是空的。
我做错了什么?

shyt4zoc

shyt4zoc1#

注意:我使用了你的代码,在应用程序的流程中没有任何变化。在你的本地机器上运行代码。点击web方法,复制url并粘贴到postman中。
我试着创建的服务基于你的代码,它是工作良好的 Postman 下面是截图和代码
尝试将下面的xml请求传递到正文,如postman中的图表所示。2同时,请确保在Postman中的Header部分将Content-Type设置为text/XML。

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Header>
    <AuthHeader xmlns="http://tempuri.org/">
      <username>admin</username>
      <password>admin</password>
    </AuthHeader>
  </soap:Header>
  <soap:Body>
    <GetFormTypes xmlns="http://tempuri.org/" />
  </soap:Body>
</soap:Envelope>

相关问题