.Net MVC / Web API 属性路由触发器下载

.Net MVC / Web API Attribute Routing triggers Download

将 WebApi 添加到 MVC 5 项目(.aspx 和 Razor 引擎)后,我试图添加属性路由,但是每当我添加此行时:

// Web API routes
config.MapHttpAttributeRoutes();

WebApiConfig 文件会产生奇怪的行为,即初始页面加载(account/login 的 MVC 路由)导致浏览器将请求视为 下载然后浏览器打开下载对话框!

对我来说,这通常是文件扩展名错误的结果,但在这种环境下,路由显然有问题,但对于我来说,我无法弄清楚我遗漏了什么。

没有 MapHttpAttributeRoutes 行,对 WebApi 控制器的 "Post" 操作的 Ajax 调用确实有效。

我会提到 Ajax 调用是通过 Angular 但是没有 angular 功能嵌入到与 /Account/Login 路由相关的页面中

我在下面发布相关的控制器和 App_Start/Config 文件以及 Web.Config 文件。

任何想法将不胜感激,我希望避免从头开始重新创建项目:-(

谢谢!

我的Api控制器

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;
using System.Web;
using System.Data;
using System.Data.Entity;
using System.Web.Http.Filters;
using mvc4.SecretService.com.Models;

namespace mvc4.SecretService.com.Controllers
{
     [RoutePrefix("api/santas")]
     public class SantasController : ApiController
     {

           private SeniorsSecretServiceEntities db = new SeniorsSecretServiceEntities();

    [HttpGet]
    [Route("list")]
    public IEnumerable<sssSantaProfile> List()
    {
        var profiles = db.sssSantaProfiles.AsEnumerable();
        return profiles;

    }
    ......
 }

WebApi配置文件:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        // THIS CAUSES THE ISSUE
        config.MapHttpAttributeRoutes();

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

        //config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
        //config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
    }
}

RouteConfig 文件如下所示:

 public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {

        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

MVC 帐户控制器如下所示:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;
using mvc4.SecretService.com.Filters;
using mvc4.SecretService.com.Models;

namespace mvc4.SecretService.com.Controllers
{
    [Authorize]
    [InitializeSimpleMembership]
    public class AccountController : Controller
    {

        public AccountController()
            : base()
        {
            ViewBag.Message = "Seniors Secret Service";

         }

        [AllowAnonymous]
        public ActionResult Login(string returnUrl)
        {
            ViewBag.Action= "Log In";
            ViewBag.ReturnUrl = returnUrl;
            return View();
         }

         [HttpPost]
         [AllowAnonymous]
         [ValidateAntiForgeryToken]
         public ActionResult Login(LoginModel model, string returnUrl)
         {
               if (ModelState.IsValid && WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe))
              {
                  return RedirectToLocal(returnUrl);
              }

              // If we got this far, something failed, redisplay form
              ModelState.AddModelError("", "The user name or password provided is incorrect.");
              return View(model);
        }
        .....
    }

根目录 Web.Config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
        <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
        <sectionGroup name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection, DotNetOpenAuth.Core">
         <section name="oauth" type="DotNetOpenAuth.Configuration.OAuthElement, DotNetOpenAuth.OAuth" requirePermission="false" allowLocation="true" />
          <section name="openid" type="DotNetOpenAuth.Configuration.OpenIdElement, DotNetOpenAuth.OpenId" requirePermission="false" allowLocation="true" />
           <section name="messaging" type="DotNetOpenAuth.Configuration.MessagingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" />
           <section name="reporting" type="DotNetOpenAuth.Configuration.ReportingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" />
     </sectionGroup>
</configSections>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="true" />
<add key="PreserveLoginUrl" value="true" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5.1">
  <assemblies>
    <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
    <add assembly="WebMatrix.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
    <add assembly="WebMatrix.WebData, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
  </assemblies>
</compilation>
<httpRuntime targetFramework="4.5" />
<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
<pages>
  <namespaces>
    <add namespace="System.Web.Helpers" />
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Optimization" />
    <add namespace="System.Web.Routing" />
    <add namespace="System.Web.WebPages" />
  </namespaces>
</pages>
<roleManager enabled="true" defaultProvider="simple">
  <providers>
    <clear />
    <add name="simple" type="WebMatrix.WebData.SimpleRoleProvider,WebMatrix.WebData" />
  </providers>
</roleManager>
<membership defaultProvider="simple">
  <providers>
    <clear />
    <add name="simple" type="WebMatrix.WebData.SimpleMembershipProvider,WebMatrix.WebData" requiresQuestionAndAnswer="false" />
  </providers>
</membership>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
  <remove name="OPTIONSVerbHandler" />
  <remove name="TRACEVerbHandler" />
  <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="DotNetOpenAuth.Core" publicKeyToken="2780ccd10d57b246" />
    <bindingRedirect oldVersion="0.0.0.0-4.3.0.0" newVersion="4.3.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="DotNetOpenAuth.AspNet" publicKeyToken="2780ccd10d57b246" />
    <bindingRedirect oldVersion="0.0.0.0-4.3.0.0" newVersion="4.3.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="itextsharp" publicKeyToken="8354ae6d2174ddca" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-5.5.6.0" newVersion="5.5.6.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Razor" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.WebPages.Razor" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
    <bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="Microsoft.Data.OData" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-5.6.4.0" newVersion="5.6.4.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="Microsoft.Data.Edm" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-5.6.4.0" newVersion="5.6.4.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="System.Spatial" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-5.6.4.0" newVersion="5.6.4.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="WebMatrix.Data" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="WebMatrix.WebData" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
  </dependentAssembly>
  <dependentAssembly>
    <assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
  </dependentAssembly>
</assemblyBinding>
<legacyHMACWarning enabled="0" />
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
</entityFramework>
<dotNetOpenAuth>
<openid>
  <relyingParty>
    <security requireSsl="false">
    </security>
    <behaviors>
      <add type="DotNetOpenAuth.OpenId.RelyingParty.Behaviors.AXFetchAsSregTransform, DotNetOpenAuth.OpenId.RelyingParty" />
    </behaviors>
  </relyingParty>
</openid>
<messaging>
  <untrustedWebRequest>
    <whitelistHosts>
    </whitelistHosts>
  </untrustedWebRequest>
</messaging>
<reporting enabled="true" />
</dotNetOpenAuth>
<uri>
<idn enabled="All" />
<iriParsing enabled="true" />
</uri>
<system.net>
<defaultProxy enabled="true" />
<settings>
</settings>
</system.net>
</configuration>

/观看次数Web.Config

<?xml version="1.0"?>
<configuration>
<configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
        <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
        <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
</configSections>

<system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
        <namespaces>
            <add namespace="System.Web.Mvc" />
            <add namespace="System.Web.Mvc.Ajax" />
            <add namespace="System.Web.Mvc.Html" />
            <add namespace="System.Web.Optimization"/>
            <add namespace="System.Web.Routing" />
        </namespaces>
    </pages>
</system.web.webPages.razor>

<appSettings>
    <add key="webpages:Enabled" value="false" />
</appSettings>

<system.web>
    <httpHandlers>
        <add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
    </httpHandlers>

    <pages
        validateRequest="false"
        pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
        pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
        userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
        <controls>
            <add assembly="System.Web.Mvc, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
        </controls>
    </pages>
</system.web>

<system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
    <modules>
        <remove name="Session" />
        <add name="Session" type="System.Web.SessionState.SessionStateModule"/>
    </modules>
    <handlers>
        <remove name="BlockViewHandler"/>
        <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
    </handlers>
</system.webServer>
</configuration>

当我将同一行代码 config.MapHttpAttributeRoutes(); 添加到我的 MVC 5 项目中的 WebApiConfig 文件时,我遇到了完全相同的行为。通过更改 Global.asax 文件解决了该问题。正如这篇关于添加 attribute routing in ASP.NET 的文章中启用属性路由标题下所述,您可以检查以下行:

WebApiConfig.Register(GlobalConfiguration.Configuration);

在Global.asax中替换为:

GlobalConfiguration.Configure(WebApiConfig.Register);

一旦我在 Global.asax 我的 MVC 5 项目 运行 中正确地进行了此更改,就不会出现奇怪的下载对话框显示。正如文章中所述,我已经从 Web API 1 模板迁移了我的 MVC 5 项目。我通过添加 Web API 2 NuGet 包开始在我的项目中使用 Web API 2。

文章内容如下:

注意:从 Web 迁移 API1

Web API 2 之前,Web API 项目模板生成的代码如下:

protected void Application_Start()
{
    // WARNING - Not compatible with attribute routing.
    WebApiConfig.Register(GlobalConfiguration.Configuration);
}

如果启用属性路由,此代码将抛出异常。如果升级现有 Web API 项目以使用属性路由,请确保将此配置代码更新为以下内容:

protected void Application_Start()
{
    // Pass a delegate to the Configure method.
    GlobalConfiguration.Configure(WebApiConfig.Register);
}