简体   繁体   English

如何在本地 IIS 中部署 WebAPI 项目

[英]How to deploy WebAPI project in Local IIS

I have created a WebApi project with EF6,it is working good in local.我用 EF6 创建了一个 WebApi 项目,它在本地运行良好。 I have published in local IIS.我已经在本地 IIS 中发布了。 But I am getting " HTTP Error 404.0 - Not Found " error after publishing但我在发布后收到“ HTTP Error 404.0 - Not Found ”错误

I am using VS2015 and IIS7.5 .我正在使用 VS2015 和 IIS7.5 。 Am I missing something.我是不是错过了什么。 Below is the code.下面是代码。

  • WebAPiCOnfig.CS WebAPI配置文件
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json.Serialization;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using WebApiContrib.Formatting.Jsonp;
using System.Web.Http.Cors;

namespace WebAPIDemo
{
    public class CustomJsonFormatter : JsonMediaTypeFormatter {
        public CustomJsonFormatter()
        {
            this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
        }
        public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)
        {
            base.SetDefaultContentHeaders(type, headers, mediaType);
            headers.ContentType = new MediaTypeHeaderValue("application/json");
        }
    }

    public static class WebApiConfig
    {

        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
            config.Formatters.Add(new CustomJsonFormatter());
            EnableCorsAttribute cors=new
                EnableCorsAttribute("*", "*", "*");
            config.EnableCors(cors);
        }
    }
}

  • Global.ascx Global.ascx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace WebAPIDemo
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {

            RouteTable.Routes.RouteExistingFiles = true;
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}

  • EmployeesController.cs员工控制器.cs

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using WebAPIDbConnect;

namespace WebAPIDemo.Controllers
{
    public class employeesController : ApiController
    {

        public HttpResponseMessage GetEmployee()
        {
            EmpEntities entities = new EmpEntities();
            var employees = entities.employees.ToList();
            var msg = Request.CreateResponse(HttpStatusCode.Accepted, employees);
            return msg;
        }
        [Route("api/employees/GetFirstEmp")]
        public HttpResponseMessage Get()
        {
            EmpEntities entities = new EmpEntities();
            var employees = entities.employees.FirstOrDefault();
            var msg = Request.CreateResponse(HttpStatusCode.Accepted, employees);
            return msg;
        }


        public employee GetEmployeeById(int id)
        {
            EmpEntities entities = new EmpEntities();
            return entities.employees.FirstOrDefault(x => x.id == id);
        }

        [HttpPost]
        public HttpResponseMessage PostEmployee([FromBody]employee emp)
        {
            try
            {
                using (EmpEntities entities = new EmpEntities())
                {
                    entities.employees.Add(emp);
                    entities.SaveChanges();
                    var message = Request.CreateResponse(HttpStatusCode.Created, emp);
                    message.Headers.Location = new Uri(Request.RequestUri + emp.id.ToString());
                    return message;
                }
            }
            catch (Exception ex)

            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
            }
        }

        [HttpDelete]
        public HttpResponseMessage DeleteEmployee(int id)
        {
            try
            {
                using (EmpEntities entities = new EmpEntities())
                {
                    var employee = entities.employees.FirstOrDefault(x => x.id == id);
                    if (employee != null)
                    {
                        entities.employees.Remove(employee);
                        entities.SaveChanges();
                        var message = Request.CreateResponse(HttpStatusCode.OK,"Deleteed Successfully!!");
                        return message;
                    }
                    else
                    {
                        return Request.CreateErrorResponse(HttpStatusCode.NotFound,"Emp not found :"+id);
                    }
                }
            }
            catch (Exception ex)

            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
            }
        }

        [HttpPut]
        public HttpResponseMessage EditEmployee(int id,[FromBody]employee emp)
        {
            try
            {
                using (EmpEntities entities = new EmpEntities())
                {
                    var eachEmployee = entities.employees.FirstOrDefault(x => x.id == id);
                    if (eachEmployee != null)
                    {
                        eachEmployee.id = emp.id;
                        eachEmployee.ename = emp.ename;
                        eachEmployee.dept_id = emp.dept_id;
                        entities.SaveChanges();
                        var message = Request.CreateResponse(HttpStatusCode.OK, "Updated Successfully!!");
                        return message;
                    }
                    else
                    {
                        return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Emp not found :" + id);
                    }
                }
            }
            catch (Exception ex)

            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
            }
        }
    }
}

  • Web.Config网页配置

    <?xml version="1.0" encoding="utf-8"?>
    <!--
      For more information on how to configure your ASP.NET application, please visit
      http://go.microsoft.com/fwlink/?LinkId=301879
      -->
    <configuration>
      <configSections>
        <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
        <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
      </configSections>
      <connectionStrings>
        <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-WebAPIDemo-20200317070224.mdf;Initial Catalog=aspnet-WebAPIDemo-20200317070224;Integrated Security=True" providerName="System.Data.SqlClient" />
        <add name="EmpEntities" connectionString="metadata=res://*/EmpModel.csdl|res://*/EmpModel.ssdl|res://*/EmpModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=Rupesh-PC\SA;initial catalog=employee;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
      </connectionStrings>
      <appSettings></appSettings>
      <system.web>
        <authentication mode="None" />
        <compilation targetFramework="4.5.2" />
        <httpRuntime targetFramework="4.5.2" />
      </system.web>
      <system.webServer>
        <validation validateIntegratedModeConfiguration="false" />
        <modules runAllManagedModulesForAllRequests="true" />
            <handlers>
                <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
                <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" resourceType="Unspecified" requireAccess="Script" preCondition="integratedMode,runtimeVersionv4.0" />
            </handlers>
    </system.webServer>
      <runtime>
        <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
          <dependentAssembly>
            <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
            <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
            <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-5.2.7.0" newVersion="5.2.7.0" />
          </dependentAssembly>
          <dependentAssembly>
            <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
            <bindingRedirect oldVersion="0.0.0.0-5.2.7.0" newVersion="5.2.7.0" />
          </dependentAssembly>
        </assemblyBinding>
      </runtime>
      <entityFramework>
        <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
          <parameters>
            <parameter value="mssqllocaldb" />
          </parameters>
        </defaultConnectionFactory>
        <providers>
          <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
        </providers>
      </entityFramework>
      <system.codedom>
        <compilers>
          <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
          <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />
        </compilers>
      </system.codedom>
    </configuration>
    <!--ProjectGuid: {634E49D2-4A84-422B-9EDC-EF93079475D8}-->

Local Output本地输出

After Deploy in local IIS facing below error在本地 IIS 中部署后面临以下错误

(Steps for deploy are: Publish=>InteMger=>Add Virtual Directory=>Create directory to application=>Manage =>Browse Site) (部署步骤是:发布=>InteMger=>添加虚拟目录=>创建目录到应用程序=>管理=>浏览站点)

IIS COnfig IIS配置

Have you created an application pool & mapped the website to that pool?您是否创建了应用程序池并将网站映射到该池?

Allocated the port of the website to 80?网站的端口分配到80了吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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