HttpSelfHostServer无法识别“application / x-www-form-urlencoded”请求

时间:2013-12-23 22:52:21

标签: c# asp.net .net asp.net-web-api

我正在使用.Net 4.5中的HttpSelfHostServer,它似乎只能在我使用QueryString发送请求时确定控制器和操作。如果我使用“application / x-www-form-urlencoded”它不起作用。

这是HttpSelfHostServer代码。

private static HttpSelfHostConfiguration _config;
private static HttpSelfHostServer _server;
public static readonly string SelfHostUrl = "http://localhost:8989";

internal static void Start()
{
    _config = new HttpSelfHostConfiguration(SelfHostUrl);
    _config.HostNameComparisonMode = HostNameComparisonMode.Exact;
    _config.Routes.MapHttpRoute(
        name: "API Default",
        routeTemplate: "api/{controller}/{action}",
        defaults: new { action = RouteParameter.Optional },
        constraints: null);

    _server = new HttpSelfHostServer(_config);

    _server.OpenAsync().Wait();
}

控制器代码。

public class SettingsController : ApiController
{
    [HttpPost]
    public bool Test(bool work)
    {
        return work;
    }
}

以下是尝试使用

通过REST控制台访问时获得的响应
Request URL: http://localhost:8989/api/Settings/Test
Request Method:POST
Status Code:404 Not Found
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Content-Length:9
Content-Type:application/x-www-form-urlencoded
Host:localhost:8989
Origin:chrome-extension://cokgbflfommojglbmbpenpphppikmonn
Pragma:no-cache
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 
           (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36
Form Dataview parsed
work=true
Response Headersview source
Content-Length:205
Content-Type:application/json; charset=utf-8
Date:Mon, 23 Dec 2013 22:41:10 GMT
Server:Microsoft-HTTPAPI/2.0

所以,如果我将我的请求更改为帖子到下面的网址,那就可以了。

http://localhost:8989/api/Settings/Test?work=true

为什么不是Content-Type:application / x-www-form-urlencoded work?

2 个答案:

答案 0 :(得分:2)

您的操作方法参数为bool,这是一种简单类型。默认情况下,ASP.NET Web API会从URI路径或查询字符串填充它。这就是http://localhost:8989/api/Settings/Test?work=true的原因。

当您在请求正文中发送它时,它不起作用,因为ASP.NET Web API默认将body绑定到复杂类型(类),因此正文将不会绑定到您的参数类型{{1} }。要让Web API绑定body中的简单类型,请更改您的操作方法。

bool

然后,你需要只发送正文中的值,就像这样。

public bool Test([FromBody]bool work)

答案 1 :(得分:0)

问题不在于Content-Type。其余控制台使用AJAX和CORS,请参阅http://en.wikipedia.org/wiki/Cross-origin_resource_sharing。这由请求中的Origin http标头指示。

包含SettingsController的服务器必须支持CORS。如果不是,AJAX请求将始终返回404。

支持CORS的最简单方法是始终在请求HTTP标头中返回Access-Control-Allow-Origin: *

相关问题