设置WebApi里面命名空间参数

在这种情况下:

如果没有特别处理,会报:

所以要像MVC中的控制器一下配置一个命名空间参数,webapi里面没有自带这个功能

代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Dispatcher;
using AutoData.Utility;

namespace AutoData
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();
            //config.HostNameComparisonMode = HostNameComparisonMode.Exact;
            
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            config.Routes.MapHttpRoute(
                name: "Admin Area Default",
                routeTemplate: "api/admin/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional, namespaceName = "AutoData.Areas.Admin.Controllers"  }
            );

            config.Routes.MapHttpRoute(
               name: "IndustryInsight Area Default",
               routeTemplate: "Api/IndustryInsight/{controller}/{action}/{id}",
               defaults: new { id = RouteParameter.Optional }
           );

            config.Routes.MapHttpRoute(
             name: "ComputeFormula Area Default",
             routeTemplate: "Api/ComputeFormula/{controller}/{action}/{id}",
             defaults: new { id = RouteParameter.Optional , namespaceName = "AutoData.Areas.ComputeFormula.Controllers"}
         );
            config.Services.Replace(typeof(IHttpControllerSelector), new NamespaceHttpControllerSelector(config));
        }
    }
}

最后一句设置,也可以配置在全局类里面:

 GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpControllerSelector), new NamespaceHttpControllerSelector(GlobalConfiguration.Configuration));

功能是一样的

 

NamespaceHttpConrollerSelector类

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Dispatcher;
using System.Web.Http.Routing;

namespace AutoData.Utility
{
    public class NamespaceHttpControllerSelector : IHttpControllerSelector
    {
        private const string NamespaceKey = "namespaceName";
        private const string ControllerKey = "controller";

        private readonly HttpConfiguration _configuration;
        private readonly Lazy<Dictionary<string, HttpControllerDescriptor>> _controllers;
        private readonly HashSet<string> _duplicates;

        public NamespaceHttpControllerSelector(HttpConfiguration config)
        {
            _configuration = config;
            _duplicates = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
            _controllers = new Lazy<Dictionary<string, HttpControllerDescriptor>>(InitializeControllerDictionary);
        }

        private Dictionary<string, HttpControllerDescriptor> InitializeControllerDictionary()
        {
            var dictionary = new Dictionary<string, HttpControllerDescriptor>(StringComparer.OrdinalIgnoreCase);

            // Create a lookup table where key is "namespace.controller". The value of "namespace" is the last
            // segment of the full namespace. For example:
            // MyApplication.Controllers.V1.ProductsController => "V1.Products"
            IAssembliesResolver assembliesResolver = _configuration.Services.GetAssembliesResolver();
            IHttpControllerTypeResolver controllersResolver = _configuration.Services.GetHttpControllerTypeResolver();

            ICollection<Type> controllerTypes = controllersResolver.GetControllerTypes(assembliesResolver);

            foreach (Type t in controllerTypes)
            {
                var segments = t.Namespace.Split(Type.Delimiter);

                // For the dictionary key, strip "Controller" from the end of the type name.
                // This matches the behavior of DefaultHttpControllerSelector.
                var controllerName = t.Name.Remove(t.Name.Length - DefaultHttpControllerSelector.ControllerSuffix.Length);

                //var key = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", segments[segments.Length - 1], controllerName); //旧版本
                var key = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", t.Namespace.ToString(), controllerName);    //新版本

                // Check for duplicate keys.
                if (dictionary.Keys.Contains(key))
                {
                    _duplicates.Add(key);
                }
                else
                {
                    dictionary[key] = new HttpControllerDescriptor(_configuration, t.Name, t);
                }
            }

            // Remove any duplicates from the dictionary, because these create ambiguous matches. 
            // For example, "Foo.V1.ProductsController" and "Bar.V1.ProductsController" both map to "v1.products".
            foreach (string s in _duplicates)
            {
                dictionary.Remove(s);
            }
            return dictionary;
        }

        // Get a value from the route data, if present.
        private static T GetRouteVariable<T>(IHttpRouteData routeData, string name)
        {
            object result = null;
            if (routeData.Values.TryGetValue(name, out result))
            {
                return (T)result;
            }
            return default(T);
        }

        public HttpControllerDescriptor SelectController(HttpRequestMessage request)
        {
            IHttpRouteData routeData = request.GetRouteData();
            if (routeData == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            // Get the namespace and controller variables from the route data.
            string namespaceName = GetRouteVariable<string>(routeData, NamespaceKey);
            if (namespaceName == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            string controllerName = GetRouteVariable<string>(routeData, ControllerKey);
            if (controllerName == null)
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }

            // Find a matching controller.
            string key = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", namespaceName, controllerName);

            HttpControllerDescriptor controllerDescriptor;
            if (_controllers.Value.TryGetValue(key, out controllerDescriptor))
            {
                return controllerDescriptor;
            }
            else if (_duplicates.Contains(key))
            {
                throw new HttpResponseException(
                    request.CreateErrorResponse(HttpStatusCode.InternalServerError,
                    "Multiple controllers were found that match this request."));
            }
            else
            {
                throw new HttpResponseException(HttpStatusCode.NotFound);
            }
        }

        public IDictionary<string, HttpControllerDescriptor> GetControllerMapping()
        {
            return _controllers.Value;
        }
    }
}

对它进行了一点点的修改,

旧版本的命名空间选.号的最后一个

我设置的取全名命名空间

这样设置以后会发现一起没有设置命名空间的路由会发生错误,所有WebApiConfig里面的路由必须设置命名空间

http://www.cnblogs.com/nikyxxx/p/3356659.html

http://aspnet.codeplex.com/SourceControl/changeset/view/dd207952fa86#Samples/WebApi/NamespaceControllerSelector/NamespaceHttpControllerSelector.cs

http://www.osdo.net/article/2015/01/13/160.html

http://blog.csdn.net/starfd/article/details/41728655

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于C# WinForms应用程序中建立Web API服务器,你可以按照以下步骤进行操作: 1. 首先,确保你的C# WinForms项目已经创建并正常运行。 2. 在项目中添加一个新的类文件(.cs),该文件将包含Web API的控制器代码。 3. 在控制器类中,使用System.Web.Http命名空间并继承ApiController类。 4. 在控制器类中,创建要公开的API方法。你可以使用各种HTTP动词(如GET、POST、PUT、DELETE等)来处理不同的API请求。 5. 在控制器类中,使用[Route]属性来定义API方法的路由。这将决定API方法可以通过哪个URL进行访问。 6. 在控制器类中,使用[HttpGet]、[HttpPost]等属性来定义API方法的HTTP动词。 7. 在控制器类中,实现API方法的具体逻辑。这可能包括从数据库中检索数据、处理请求参数等。 8. 在WinForms应用程序的入口点(例如Main函数)中,使用System.Web.Http.SelfHost命名空间来启动Web API服务器。 9. 在Web API服务器的启动代码中,使用HttpSelfHostConfiguration类来配置服务器设置,例如指定要监听的端口号、启用跨域访问等。 10. 在Web API服务器的启动代码中,使用HttpSelfHostServer类来创建并启动服务器。 11. 运行你的C# WinForms应用程序,并确保Web API服务器已经成功启动。 现在,你的C# WinForms应用程序中就有一个Web API服务器了,可以通过API方法来处理HTTP请求。你可以使用工具(例如Postman)来测试和调试API方法。请记住,这只是一个基本的示例,你可以根据自己的需求进行更多的定制化和功能扩展。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值