我的 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;
}
}
}
我正在使用郵遞員工具對其進行測驗。我的有效載荷主體如下所示:
<?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>
我在網上查看的所有示例(包括 Microsoft 的官方檔案)都以類似的方式執行此操作,但我的代碼不起作用。當我發送請求時,soap 標頭的值auth始終為空。
我究竟做錯了什么 ?
uj5u.com熱心網友回復:
注意:我使用您的代碼在應用程式流程中沒有任何變化。在本地機器上運行代碼。點擊web方法,復制url并粘貼到postman中。
我嘗試根據您的代碼創建服務,它在郵遞員中運行良好,下面是螢屏截圖和代碼
嘗試將以下 xml 請求傳遞給正文,如 postman 中的圖表所示。另外,請確保在 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>

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/453724.html
