是否可以仅将MediaTypeFormatter更改为JSON?

DNR*_*NRN 7 c# asp.net-web-api

我有一个web api,其中全局配置配置为使用:XmlMediaTypeFormatter

我的问题是我不会使用新的控制器来扩展这个web api,而是使用JsonMediaTypeFormatter.

是否可以仅为一个API控制器类将MediaTypeFormatter更改为JSON?

我的问题是没有返回JSON,我已经通过返回HttpResponseMessage来解释这个:

return new HttpResponseMessage
{
    Content = new ObjectContent<string>("Hello world", new JsonMediaTypeFormatter()),
    StatusCode = HttpStatusCode.OK
};
Run Code Online (Sandbox Code Playgroud)

这是我要求问题的要求.如果我有一个具有两个属性的对象:

public class VMRegistrant 
{
    public int MerchantId { get; set; }
    public string Email { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我的控制器操作将VMRegistrant作为参数:

public HttpResponseMessage CreateRegistrant(VMRegistrant registrant)
{
    // Save registrant in db...
}
Run Code Online (Sandbox Code Playgroud)

但问题是,当我用JSON调用该操作时,它失败了.

Yuv*_*kov 7

您可以让控制器返回 anIHttpActionResult并使用扩展方法HttpRequestMessageExtensions.CreateResponse<T>并指定要使用的格式化程序:

public IHttpActionResult Foo()
{
    var bar = new Bar { Message = "Hello" };
    return Request.CreateResponse(HttpStatusCode.OK, bar, new MediaTypeHeaderValue("application/json"));
}
Run Code Online (Sandbox Code Playgroud)

另一种可能性是使用该ApiController.Content方法:

public IHttpActionResult Foo()
{
    var bar = new Bar { Message = "Hello" };
    return Content(HttpStatusCode.OK, bar, new JsonMediaTypeFormatter(), new MediaTypeHeaderValue("application/json"));
}
Run Code Online (Sandbox Code Playgroud)

编辑:

一种可能性是Request通过从流中读取并使用 JSON 解析器(如 Json.NET)从 JSON 创建对象,自己从对象中读取和反序列化内容:

public async Task<IHttpActionResult> FooAsync()
{
      var json = await Request.Content.ReadAsStringAsync();
      var content = JsonConvert.DeserializeObject<VMRegistrant>(json);
}
Run Code Online (Sandbox Code Playgroud)