【问题标题】:how to fix this error WebApiConfig in Global.asax?如何在 Global.asax 中修复此错误 WebApiConfig?
【发布时间】:2015-02-13 13:39:26
【问题描述】:

这里有一个很棒的线程: How to add Web API to an existing ASP.NET MVC (5) Web Application project?

不幸的是,对我来说,Global.asax 中的 WebApiConfig 出现错误,所以我什至安装了 nugets,我该如何解决这个错误。

当前上下文中不存在名称“WebApiConfig”

Global.asax

 protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

    }

WebApiConfig

 public class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {


        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        // WebAPI when dealing with JSON & JavaScript!
        // Setup json serialization to serialize classes to camel (std. Json format)
        var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
        formatter.SerializerSettings.ContractResolver =
            new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();

    }
}

【问题讨论】:

  • @MairajAhmad 请检查更新代码
  • 是的,我已经检查过了,请添加 webapiconfig 类代码。
  • 我觉得你的命名空间有问题。
  • @dotnetstep 非常感谢它的工作
  • 是的,这就是我要代码的原因。

标签: c# asp.net asp.net-mvc api asp.net-mvc-4


【解决方案1】:

当您从其他项目复制代码时,您正在将 web api 合并到现有 mvc 项目中,所以很多时候两个项目具有不同的命名空间,因此您必须添加命名空间或更改 webapiconfig 的命名空间。

【讨论】:

    猜你喜欢
    • 2014-07-29
    • 2013-11-23
    • 1970-01-01
    • 1970-01-01
    • 2016-08-18
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多