简体   繁体   English

为什么在路由到 REST WebAPI 获取方法时需要内容类型 header?

[英]Why is content-type header needed when routing to an REST WebAPI get method?

As the example code shown below, I am trying to access the get method by calling http://localhost:51292/API/MyWebAPI/GetData/?Name=John then I receive an error saying " The request contains an entity body but no Content-Type header. The inferred media type 'application/octet-stream' is not supported for this resource. "如下所示的示例代码,我试图通过调用http://localhost:51292/API/MyWebAPI/GetData/?Name=John来访问 get 方法,然后我收到一条错误消息“请求包含实体主体但没有内容类型 header。此资源不支持推断的媒体类型“应用程序/八位字节流”。

public class MyData
{
    int ID { get; set; }
}
public class MyDataDTO : MyData
{
    string Name { get; set; }
}

public class MyWebAPIController : ApiController
{
    [AllowAnonymous]
    [HttpGet]
    public IHttpActionResult GetData(MyDataDTO publicInfo)
    {
        
        return Ok(publicInfo);
    }
}

I don't find any proper reason on why it requires the content type, maybe it has something to do with the API controller, or the routing?我找不到任何适当的理由说明它为什么需要内容类型,也许它与 API controller 或路由有关? My routing is showen as below:我的路由如下图:

    HttpConfiguration config = new HttpConfiguration();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "API/{controller}/{action}"
    );
    app.UseWebApi(config);

The solution was just to add [FromUri] before the MyDataDTO object type for the Get method, such:解决方案只是在 Get 方法的MyDataDTO object 类型之前添加[FromUri] ,例如:

[AllowAnonymous]
[HttpGet]
public IHttpActionResult GetData([FromUri] MyDataDTO publicInfo)
{
    
    return Ok(publicInfo);
}

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

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