2013-06-20 190 views
2

总是在有效请求上获得400 Bad Request。也许有些提示?需要解决这个非常糟糕。ASP.NET Web API HTTP 400错误请求

控制器

public class MyController : ApiController 
{ 
    public IEnumerable<string> GetAll(string language) 
    { 
     return new [] {"a", "b", "c"}; 
    } 
} 

请求

$.ajax({ 
     type: "POST", 
     url: "http://localhost:5378/Api/MyController/GetAll", 
     dataType: "json", 
     contentType: "application/json; charset=utf-8", 
     data: { "language": language }, 
     cache: false, 
     complete: function (xhr) { 
      console.output(xhr.status.toString()); 
     } 
    }); 

WebApiConfig

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

    var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml"); 
    config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType); 
} 

Webconfig

<?xml version="1.0" encoding="utf-8"?> 
<configuration> 
    <configSections> 
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /> 
    </configSections> 
    <connectionStrings> 
    <add name="DataConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-web-data;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\web-data.mdf" /> 
    <add name="AuthConnection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-web-auth;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\web-auth.mdf" /> 
    </connectionStrings> 
    <appSettings> 
    <add key="webpages:Version" value="2.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> 
    <roleManager enabled="true" defaultProvider="SimpleRoleProvider"> 
     <providers> 
     <clear /> 
     <add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> 
     </providers> 
    </roleManager> 
    <membership defaultProvider="SimpleMembershipProvider"> 
     <providers> 
     <clear /> 
     <add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /> 
     </providers> 
    </membership> 
    <httpRuntime targetFramework="4.5" /> 
    <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> 
    <compilation debug="true" /> 
    </system.web> 
    <system.webServer> 
    <directoryBrowse enabled="true" /> 
    <validation validateIntegratedModeConfiguration="false" /> 
    <handlers> 
     <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" /> 
     <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" /> 
     <remove name="ExtensionlessUrlHandler-Integrated-4.0" /> 
     <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" /> 
     <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" /> 
     <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /> 
    </handlers> 
    </system.webServer> 
    <runtime> 
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> 
     <dependentAssembly> 
     <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" /> 
     <bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" /> 
     </dependentAssembly> 
     <dependentAssembly> 
     <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /> 
     <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" /> 
     </dependentAssembly> 
     <dependentAssembly> 
     <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" /> 
     <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" /> 
     </dependentAssembly> 
     <dependentAssembly> 
     <assemblyIdentity name="System.Web.WebPages.Razor" publicKeyToken="31bf3856ad364e35" culture="neutral" /> 
     <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" /> 
     </dependentAssembly> 
    </assemblyBinding> 
    </runtime> 
    <entityFramework> 
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> 
    </entityFramework> 
    <system.webServer> 
    <staticContent> 
     <mimeMap fileExtension=".json" mimeType="application/json" /> 
    </staticContent> 
    </system.webServer> 
</configuration> 
+0

一个明显的问题是,你POST'ing到仅支持GET控制器操作。但是,这应该导致405方法不允许。 400错误请求表示您请求的URL没有路由(例如,没有控制器操作可以与URL匹配)。 –

回答

5

Web api使用动词来标识动作,除非您另行配置它。

GETALL没有在网址必要的,因为网络API会自动寻找与获取启动控制器上的方法,当您使用GET HTTP动词

它容易混淆的的ASP.NET MVC路由与网页api。

请求:

$.ajax({ 
    type: "POST", 
    url: "http://localhost:5378/Api/MyController", 
    dataType: "json", 
    contentType: "application/json; charset=utf-8", 
    data: { "language": language }, 
    cache: false, 
    complete: function (xhr) { 
     console.output(xhr.status.toString()); 
    } 
}); 
+0

顺便提一句,既然你发布了数据,你需要命名你的方法以Post开头,或者在方法上使用AcceptVerbs属性 –

3

你的控制器类叫做MyController。因此,您的网址应该调用My而不是MyController

type: "GET", 
url: "http://localhost:5378/Api/My/" 

Microsoft provides some good information了解路由约定。

编辑:正如马丁指出,如果你的方法是“get”方法,那么你的Ajax调用不应指定POST,它并不需要指定,因为命名约定的GetAll

+0

对不起,在这个示例中...... –

+1

除了这个修复之外,ajax请求应该有'type:“GET”'。 –