RavenDb返回错误的请求,无法在第二个API调用时弄清楚该怎么做

本文关键字:调用 API 弄清楚 第二个 错误 返回 请求 RavenDb | 更新日期: 2023-09-27 18:27:22

在使用嵌入式RavenDb作为数据库和IIS express开发和调试.NET Web API时遇到问题。对API的第一次调用正常执行并返回所有结果。这次通话也不例外。然而,任何连续的调用都会导致400错误的请求响应,其正文包含错误文本:"无法确定要做什么"。错误是可重复的,但您必须在调试器中重新启动API。

为了连接到RavenDb,我创建了自己的控制器,它继承了ApiController:

using Raven.Client;
using Raven.Client.Embedded;
using Raven.Database.Server;
using System;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Controllers;
public class RavenController : ApiController {
    #region Declarations
    private static readonly Lazy<IDocumentStore> LazyDocStore = new Lazy<IDocumentStore>( () => {
        var docStore = new EmbeddableDocumentStore { 
            ConnectionStringName="RavenDB" 
        };
        docStore.Initialize();
        return docStore;
    } );
    #endregion
    #region Properties
    public IDocumentStore Store {
        get { return LazyDocStore.Value; }
    }
    public IAsyncDocumentSession Session { get; set; }
    #endregion
    #region Overridden methods
    public async override Task<HttpResponseMessage> ExecuteAsync( 
        HttpControllerContext controllerContext, CancellationToken cancellationToken ) {
        using (this.Session = this.Store.OpenAsyncSession()) {
            var result = await base.ExecuteAsync( controllerContext, cancellationToken );
            await Session.SaveChangesAsync();
            return result;
        }
    }
    #endregion
}

该控制器在RavenDb网站上作为样本展示。

连接字符串定义为:

<add name="RavenDB" connectionString="DataDir=~'App_Data'albumDB"/>

WebAPI控制器如下所示:

using Raven.Client;
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
public class AlbumsController : RavenController {
    #region Public methods
    // GET api/Albums/GetAllAlbums
    public async Task<HttpResponseMessage> GetAllAlbums() {
        HttpResponseMessage msg = null;
        try {
            var albums = await Session.Query<Album>().ToListAsync();
            msg = Request.CreateResponse( HttpStatusCode.OK, albums );
        }
        catch (Exception ex) {
            msg = Request.CreateErrorResponse( HttpStatusCode.InternalServerError, ex );
        }
        return msg;
    }
    #endregion
}

相册类定义为:

public class Album {
    public string Name { get; set; }
    public string Publisher { get; set; }
}

我在谷歌上搜索了一下,但没有发现任何对我有意义的东西。有什么关于我做错了什么的建议吗?

RavenDb返回错误的请求,无法在第二个API调用时弄清楚该怎么做

这是一个适用于嵌入式ravendb的工作配置:

在全球.asax:

protected void Application_Start()
        {
            //AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            InitializeDocumentStore();
        }
        public static IDocumentStore Store { get; private set; }
        private static void InitializeDocumentStore()
        {
            NonAdminHttp.EnsureCanListenToWhenInNonAdminContext(8282);
            Store = new EmbeddableDocumentStore
            {
                ConnectionStringName = "RavenDB",
                UseEmbeddedHttpServer = Convert.ToBoolean(ConfigurationManager.AppSettings["ravenhost"]),
                Conventions = { IdentityPartsSeparator = "-" },
                Configuration = { Port = 8282 }
            };
            Store.Initialize();
        }

在Base Api控制器中:

public IAsyncDocumentSession Session { get; set; }
        public async override Task<HttpResponseMessage> ExecuteAsync(
            HttpControllerContext controllerContext, CancellationToken cancellationToken)
        {
            using (Session = WebApiApplication.Store.OpenAsyncSession())
            {
                var result = await base.ExecuteAsync(controllerContext, cancellationToken);
                await Session.SaveChangesAsync();
                return result;
            }
        }

在您的Apicontroller中:

public async Task<BaseResponse<DocumentState>> GetById(string id)
    {
        try
        {
            _answer.SingleResult = await Session.LoadAsync<DocumentState>(id);
            _answer.Success = true;
        }
        catch (Exception ex)
        {
            _answer.ErrorResponse = ex;
        }
        return _answer;
    }

忽略answer的东西,这是我的自定义返回类型。然而,这部作品在当地很受欢迎,在azure上发布时也很受欢迎。

最后要注意的是,我的网络配置包含以下内容:

<appSettings>
<add key="Raven/Port" value="8282" />
    <add key="ravenhost" value="true" />
</appSettings>

希望这能帮助