简体   繁体   中英

ASP.NET legacy app using MassTransit fails to send message on second try

I have an ASP.NET 4.7.2 app and I'm not able to migrate to new .NET version yet.

Right now we are using Masstransit 6.3.2.

What happens is that we create a bus like this in my Global.asax.cs :

busControl = Bus.Factory.CreateUsingRabbitMq((cfg) => 
                {
                    cfg.Host(_settings.Host, _settings.VirtualHost, hfg =>
                    {
                        hfg.Password(_settings.Password);
                        hfg.Username(_settings.UserName);
                    });
                });
container.RegisterInstance<IBusControl>(busControl);
container.RegisterInstance<IBus>(busControl);

Bus is passed to the container ( IUnityContainer ) and injected into a controller:

[RoutePrefix("api/Message")]
public class MessageController : ApiController
{
    private readonly IBus bus;

    public MessageController(IBus bus)
    {
        this.bus = bus;
    }

    [HttpPost()]
    [ResponseType(typeof(void))]
    [Route(nameof(SendTestMessage))]
    public async Task<IHttpActionResult> SendTestMessage(TestMessage message)
    {
        if (message == null)
            return BadRequest();

        try
        {
            var endpoint = await bus.GetSendEndpoint(new Uri("exchange:testQueue"));
            await endpoint.Send(message);

            return Ok();
        }
        catch (Exception ex)
        {
            Logger.Fatal(ex, "HttpRequest {requestname} failed", nameof(SendTestMessage));
            return StatusCode(HttpStatusCode.InternalServerError);
        }
    }
}

First time the action is called, everything is fine and message is passed to the RabbitMq queue. On the second attempt, it fails with an exception.

There is no stacktrace to the exception. Source of the exception is System.Web .

System.NullReferenceException
HResult=0x80004003
Message=Object reference not set to an instance of an object
This exception was originally thrown at this call stack:
System.Web.ThreadContext.AssociateWithCurrentThread(bool)

So fix was quite easy.

I just changed

var endpoint = await bus.GetSendEndpoint(new Uri("exchange:testQueue"));

To

var endpoint = await bus.GetSendEndpoint(new Uri("exchange:testQueue")).ConfigureAwait(false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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