繁体   English   中英

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

[英]HttpSelfHostServer not recognizing “application/x-www-form-urlencoded” Requests

我正在使用.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

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

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

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

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

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

public bool Test([FromBody]bool work)

然后,您将需要仅发送正文中的值,如下所示。

=true

问题不在于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: *

暂无
暂无

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

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