CoreWCF SOAP12 АутентификацияC#

Место общения программистов C#
Ответить
Anonymous
 CoreWCF SOAP12 Аутентификация

Сообщение Anonymous »

У меня есть основное веб -приложение ASP.NET, которое я использую для размещения сервиса WCF Core. Это моя программа.cs: < /p>
using System.Text;
using CoreWCF;
using CoreWCF.Channels;
using CoreWCF.Configuration;
using CoreWCF.Description;
using Microsoft.AspNetCore.Authentication;
using WebApplication1;

const string HOST_IN_WSDL = "localhost";

var builder = WebApplication.CreateBuilder(args);

// Add WSDL support
builder.Services.AddServiceModelServices().AddServiceModelMetadata();

// Use the scheme/host/port used to fetch WSDL as that service endpoint address in generated WSDL
builder.Services.AddSingleton();

builder.Services.AddHttpContextAccessor();
builder.Services.AddAuthentication("MyScheme")
.AddScheme("MyScheme", null);

builder.Services.AddAuthorization();

var app = builder.Build();

app.UseServiceModel(builder =>
{

builder.AddService(typeof(MyService), (serviceOptions) =>
{
serviceOptions.BaseAddresses.Add(new Uri($"https://{HOST_IN_WSDL}/MyService"));
})
.AddServiceEndpoint(typeof(MyService),
typeof(IMyService),
new WSHttpBinding(SecurityMode.Transport), // SOAP 1.2
new Uri("", UriKind.RelativeOrAbsolute), (Uri)null, null);

});

// Enable WSDL for http & https
var serviceMetadataBehavior = app.Services.GetRequiredService();
serviceMetadataBehavior.HttpGetEnabled = serviceMetadataBehavior.HttpsGetEnabled = true;

app.MapGet("/", () => "Hello World!");

app.UseAuthentication();
app.UseAuthorization();

app.Run();
< /code>
myservice.cs:
internal class MyService : IMyService
{
public async Task HelloWorld(string name)
{
await Task.Delay(1);
return $"Hello, {name}!";
}
}
< /code>
imyservice.cs:
using CoreWCF;

[ServiceContract(Namespace = "http://schemas.test.com/myengine")]
public interface IMyService
{
[OperationContract(AsyncPattern = true)]
Task HelloWorld(string name);
}
< /code>
myauthenticationhandler.cs:
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Options;
using System.Security.Claims;
using System.Text.Encodings.Web;

namespace WebApplication1
{
public class MyAuthenticationHandler : AuthenticationHandler
{
public MyAuthenticationHandler(
IOptionsMonitor options,
ILoggerFactory logger,
UrlEncoder encoder
)
: base(options, logger, encoder)
{
}

protected override async Task HandleAuthenticateAsync()
{
// Retrieve the current principal
var currentPrincipal = System.Web.HttpContext.Current.User;

// Create a ClaimsPrincipal if the current principal is not a ClaimsPrincipal
var claimsPrincipal = currentPrincipal as ClaimsPrincipal ?? new ClaimsPrincipal(currentPrincipal);
return AuthenticateResult.Success(new AuthenticationTicket(claimsPrincipal, Scheme.Name));
// return AuthenticateResult.Fail("Invalid credentials");
}
}
}
< /code>
Когда я называю свою службу с SoapUi, я получаю эту ошибку: < /p>

http/1.1 500 Внутренний серверный содержимое содержимого-Type /plain;
charset = utf-8 Дата: ср, 06 августа 2025 14:00:58 GMT Server: KESTRING СРЕДНА:> СВЕРИНГ. Chunked < /p>
system.invalidoperationException: Ни один обработчик аутентификации не зарегистрирован для
для схемы «договориться». Зарегистрированные схемы:
myscheme. Вы забыли позвонить
microsoft.aspnetcore.authentication.authenticationservice.authenticateasync(httpcontext
Context, String Scheme) at
corewcf.channels.requestdelegatehandler.handlerequest(httpcontext Ваш /> microsoft.aspnetcore.authentication.authenticationmiddleware.invoke(httpcontext
context) at
corewcf.channels.servicemodelhttpmiddleware.invokeasync(httpcontext
context) at
CoreWCF.Channels.MetadataMiddleware.InvokeAsync(HttpContext context)

at
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext
context)
HEADERS
======= Connection: Keep-Alive Host: Localhost: 7075 Пользовательский агент: Apache-Httpclient /4.5.5 (Java /17.0.12) Принятие: GZIP, дефтат
content-type:
Application/soap+xml; charset=utf-8;action="http://schemas.test.com/myengine/imyservice/helloworld ". Что мне нужно изменить, чтобы остановить это от проверки схемы переговоров?

Подробнее здесь: https://stackoverflow.com/questions/797 ... entication
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»