加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 是否可以将MediaTypeFormatter更改为只有一个类的JSON?

发布时间:2020-12-15 07:41:02 所属栏目:百科 来源:网络整理
导读:我有一个web api,其中全局配置配置为使用: XmlMediaTypeFormatter 我的问题是我不会使用新的控制器扩展这个web api,而是使用JsonMediaTypeFormatter. 是否可以仅为一个API控制器类将MediaTypeFormatter更改为JSON? 我的问题是没有返回JSON,我已经通过返回H
我有一个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
};

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

public class VMRegistrant 
{
    public int MerchantId { get; set; }
    public string Email { get; set; }
}

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

public HttpResponseMessage CreateRegistrant(VMRegistrant registrant)
{
    // Save registrant in db...
}

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

解决方法

您可以让控制器返回IHttpActionResult并使用扩展方法 HttpRequestMessageExtensions.CreateResponse<T>并指定要使用的格式化程序:
public IHttpActionResult Foo()
{
    var bar = new Bar { Message = "Hello" };
    return Request.CreateResponse(HttpStatusCode.OK,bar,new MediaTypeHeaderValue("application/json"));
}

另一种可能性是使用1(System.Net.HttpStatusCode,0,System.Net.Http.Formatting.MediaTypeFormatter,System.Net.Http.Headers.MediaTypeHeaderValue)" rel="nofollow" target="_blank">ApiController.Content方法:

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

编辑:

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读