Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
551 views
in Technique[技术] by (71.8m points)

asp.net web api - AttributeRouting not working with HttpConfiguration object for writing Integration tests

I'm creating some integration tests following the ideas outlined here: http://www.strathweb.com/2012/06/asp-net-web-api-integration-testing-with-in-memory-hosting/

When I try to register routes from a hand crafted HttpConfiguration object I'm getting the following error: "The constraint entry 'inboundHttpMethod' on the route with route template 'api/Contacts/{id}' must have a string value or be of a type which implements 'IHttpRouteConstraint'."

Sample code: Controller:

 [RoutePrefix("api")]
    public class ContactsController : ApiController
    {
        [GET("Contacts/{id}",RouteName="GetContactsById")]
        public ContactDTO Get(int id)
        {
      return new ContactDTO{ ID =1, Name="test"};
        }
    }
}

TestClass (MSTest):

 [TestClass]
    public class ContactsTest
    {
        private string _url = "http://myhost/api/";
        private static HttpConfiguration config = null;
        private static HttpServer server = null;
        private HttpRequestMessage createRequest(string url, string mthv, HttpMethod method)
        {
             var request = new HttpRequestMessage();
            request.RequestUri = new Uri(_url + url);
            request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(mthv));
            request.Method = method;
            return request;
        }
        private HttpRequestMessage createRequest<T>(string url, string mthv, HttpMethod method, T content, MediaTypeFormatter formatter) where T : class
        {
            HttpRequestMessage request = createRequest(url, mthv, method);
            request.Content = new ObjectContent<T>(content, formatter);

            return request;
        }

        [ClassInitializeAttribute]
        public static void ClassInitialize(TestContext ctx)
        {
            config = new HttpConfiguration();
            config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
            config.Services.Replace(
                typeof(IDocumentationProvider), new DocProvider());

            config.Services.Replace(
                typeof(IApiExplorer),
                new VersionedApiExplorer(config));

            config.Services.Replace(
                typeof(IHttpControllerSelector),
                new VersionHeaderVersionedControllerSelector
                    (config)
                    );
            AttributeRoutingHttpConfig.RegisterRoutes(config.Routes);
            WebApiConfig.Register(config);
            server = new HttpServer(config);
        }

        public static void ClassCleanup()
        {
            config.Dispose();
            server.Dispose();
        }

        [TestMethod]
        public void RetrieveContact()
        {
            var request = createRequest("Contacts/12","application/json",HttpMethod.Get);
            var client = new HttpClient(server);

            using (HttpResponseMessage response = client.SendAsync(request).Result)
            {
                Assert.IsNotNull(response.Content);
            }
        }
    }

The error occurs on the line "client.SendAsync". I inspected config.Routes and the datatype for the "Constraints" for ''inboundHttpMethod' ' is AttributeRouting.Web.Http.WebHost.Constraints.InboundHttpMethodConstraint It appears that a string value is expected. Any help would be much appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Had the same problem. Found the answer here:

https://github.com/mccalltd/AttributeRouting/issues/191

You need to replace

AttributeRoutingHttpConfig.RegisterRoutes(config.Routes);

with

config.Routes.MapHttpAttributeRoutes(cfg =>
{
   cfg.InMemory = true;
   cfg.AutoGenerateRouteNames = true;
   cfg.AddRoutesFromAssemblyOf<ContactsController>();// Or some other reference...
});

I found I also needed the AutoGenerateRouteNames part, too.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...