简体   繁体   中英

Return either xml or json from MVC web api based on request returns 404 error

Using the URL http://localhost/api/Student I get a list of students in XML format.

What I would like to do is have the option to return either json or xml based on the request. So for json, it would be;

http://localhost/api/Student.json

and for XML, it would be;

http://localhost/api/Student.xml

likewise;

http://localhost/api/Student.json/1/
http://localhost/api/Student.xml/1/

I have implemented this in my WebApiConfig.cs file.

 StructuremapWebApi.Start();


 config.Formatters.JsonFormatter.AddUriPathExtensionMapping("json", "application/json");
 config.Formatters.XmlFormatter.AddUriPathExtensionMapping("xml", "text/xml");
 // Web API routes
 config.MapHttpAttributeRoutes();

 config.Routes.MapHttpRoute(
 name: "DefaultApi",
 routeTemplate: "api/{controller}/{id}",
 defaults: new { id = RouteParameter.Optional }
 );

 config.Routes.MapHttpRoute(
 name: "Api UriPathExtension ID",
 routeTemplate: "api/{controller}/{id}.{ext}",
 defaults: new { id = RouteParameter.Optional, extension = 
 RouteParameter.Optional }
 );

 config.Routes.MapHttpRoute(
 name: "Api UriPathExtension",
 routeTemplate: "api/{controller}.{extension}/{id}",
 defaults: new { id = RouteParameter.Optional, extension = 
 RouteParameter.Optional }
 );

Once I call one of the links with the extension it returns a HTTP Error 404.0 - Not Found .

Am I missing something? Any help please.

I'm not a dotnet developer but my guess is that AddUriPathExtensionMapping isn't doing what you think it's doing. I assume your routes aren't getting registered with the .json or .xml file types like you think which is why you get a 404.

So you'll either have to figure out how to add the pattern matching you need the proper way or take another approach.

Usually the way an API supports multiple formats is through HTTP headers.

For JSON the client will send the headers:

Content-Type: application/json
Accepts: application/json

For XML, typically this:

Content-Type: application/json
Accepts: application/xml

Assuming that you still want to send a JSON body to your API when sending POSTs, PUTs or PATCHes but simply expect to receive the response in XML format. If you wanted to send over XML then you'd change Content-Type to application/xml

Of course, you have to support these headers yourself server-side, usually by adding middleware that serializes the responses and requests to and from the format that you need.

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