简体   繁体   中英

How to specify the expected response content-type in a http request?

My client needs to get his data in a.Net Dataset data type represented in XML format. Currently my api returns a List in Json type. How can I make such this request?

In client (which is Asp.NET Web API):

var myHttpClient = new HttpClient();
myHttpClient.DefaultRequestHeaders.Add("Accept", "application/xml");
myHttpClient.DefaultRequestHeaders.Add("MyExpected-Content-Type", "Dataset");
var response = await myHttpClient.GetAsync(apiUrl);

In server (which is Asp.NET Core Web API):

if (Request.Headers["MyExpected-Content-Type"] == "Dataset")
{
    DataSet ds = new DataSet();
    // ...
    return Ok(ds.GetXml());
}
else
{
    var lst = new List<Gifts>();
    // ...
    return Ok(lst);
}

Does this what you want? I found this solution to return XML, and this answer for converting a model to xml string.

public IActionResult getHeader() {
            if (Request.Headers["MyExpected-Content-Type"] == "Dataset") {
                var user = new UserModel { age= 1, name="user1" };
                var writer = new StringWriter();
                var serializer = new XmlSerializer(typeof(UserModel));
                serializer.Serialize(writer, user);
                string xml = writer.ToString();
                return new ContentResult
                {
                    ContentType = "application/xml",
                    Content = xml,
                    StatusCode = 200
                };
            }
            else
            {
                var xml = "<result><value>hello</value></result>";
                return new ContentResult
                {
                    ContentType = "application/xml",
                    Content = xml,
                    StatusCode = 200
                };
            }
            
        }

Here's my testing result:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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